CS61B - Iterator
(码字不易,感觉有点用的话可以点个赞嘛~)
Iterator是什么?
看了CS61B这部分的网课两遍,感觉要好好记录下来,不然接下来还是容易忘。
首先,究竟是什么原因让我们揪出来了Iterator这个东西呢?我们先看一段代码:
//assume we have an ArrayList called AList, which contains String type items
//we want to create a method to print out all the items in the list
public void printAList(ArrayList<String> ALits) {
for(String x : AList) {
System.out.println(x);
}
}
这个方法可以打印出AList中的每个元素,运行结果如图所示:
我们自己创建一个ArrayList!
我们不调用java.util.ArrayList, 而是自己创建一个ArrayList,正好可以借用之前的AList(CS61B之前的课上跟着做的)来用一用这个方法:
public class AList<item> {
private item[] items;
private int size;
/** Creates an empty list. */
public AList() {
items = (item[]) new Object[100]; //create a array which length is 100 (0-99)
size = 0;
}
/** Inserts X into the back of the list. */
/*
when you want to add a new value in this list, you'll find that
it go into position size!
e.i. [0,0,0,0,0,0,0,0]
index: 0 1 2 3 4 5 6 7
if you want to add value, for example, add a[0] = 5
it happens to be the items[size].
*/
/** resizes the underlying array to the target capacity */
private void resize(int capacity){
/**if we type -> item[] a = new item[capacity];
* error! type item cannot instantiated!
* Java cannot instantiated generic(通用) type
* */
item[] a = (item[]) new Object[capacity];
System.arraycopy(items, 0, a, 0, size);
items = a;
}
public void addLast(item x) {
/** add items when the array is full (size == items.length)
*/
if(size == items.length){
resize(size * 2); //uses multiply to set size, to save time consuming
}
items[size] = x;
size += 1;
}
/**we define usage ratio R = size/items.length
* if R < 0.25, we have to half array size
* i.e. we use an array, which length i