迭代器
迭代器使用时的注意点
1、不能在前面加’*'来得到实例
2、直接打印迭代器意义不大
3、只能通过next(双向迭代器还有previous)方法来得到实例
4、实现了迭代器的类可以用foreach语法
默认迭代器的定向元素注意点(以双向迭代器为例)
it为迭代器,数字为迭代器索引
自己实现迭代器(以单向迭代器为例)
package Test;
import java.util.*;
class MyList<T> implements Iterable<T> {
static final private int DEFAULT_LENGTH = 100;
private int NOW_LENGTH=100;
private int end = 0;
T[] list;
//构造部分
public MyList(int length) {
list = (T[]) new Object[length];
}
public MyList() {
this(DEFAULT_LENGTH);
}
//Iterator实现部分
public Iterator<T> iterator() {
class MyIterator implements Iterator {
private int address = 0;
public boolean hasNext() {
return address != end;
}
public T next() {
return list[address++];
}
}
return new MyIterator();
}
//功能实现部分
public void resize(int length){
T[]temp = (T[]) new Object[length];
System.arraycopy(list,0,temp,0,end);
list=temp;
}
public void add(T obj) {
list[end++] = obj;
if(end==NOW_LENGTH)resize(NOW_LENGTH+10);
}
public T get(int index) {
return list[index];
}
public int getSize(){
return end;
}
public boolean contains(T obj) {
for (T temp : this) {
if (temp.equals(obj)) return true;
}
return false;
} //找到返回true,反之返回false
public boolean remove(T obj) {
for (int i = 0; i < end; i++) {
if (list[i].equals(obj)) {
for (int j = i + 1; j < end; j++) list[j - 1] = list[j];
end--;
return true;
}
}
return false;
} //成功返回true,反之返回false
public int indexOf(T obj) {
int i = 0;
for (T temp : this) {
if (temp.equals(obj)) return i;
i++;
}
return -1;
} //找到就返回数组对应位置,反之返回-1
public void print() {
for (T temp : this) {
System.out.print(temp.toString()+" ");
}
System.out.println();
}
}
public class Test
{
public static void main(String[] args)
{
//按Integer类型test
MyList<Integer> list=new MyList<Integer>();
Random rad=new Random();
//随机初始化
for(int i=0;i<15;i++)list.add(rad.nextInt(100));
list.print();
//随机移除一个元素
list.remove(list.get(rad.nextInt(list.getSize())));
//迭代器foreach打印
Iterator<Integer> i=list.iterator();
while(i.hasNext())System.out.print(i.next()+" ");
}
}
依此实现,既可以生成该存储类的迭代器来循环遍历,也可以像print方法一样用foreach语法
自己实现迭代器时,其指向元素和迭代器索引将根据实现来决定