解析
网上到处都是
示例代码
package abc;
interface Iterator {//定义迭代器接口
public boolean hasNext();
public Object next();
}
class ConcreteIterator<T> implements Iterator {//定义包括泛型的实际迭代器
private MyList<T> mylist = null;
private int index;
public ConcreteIterator(MyList<T> mylist) {
super();
this.mylist = mylist;
}
@Override
public boolean hasNext() {
if (index >= mylist.getSize()) {
return false;
} else {
return true;
}
}
@Override
public T next() {
T object = (T) mylist.getElementAt(index);
index++;
return object;
}
}
interface MyList<T> {//定义一个容器接口
public void addElement(T obj);
public Object getElementAt(int index);
public Iterator iterator();
public int getSize();
}
class MyArrayList<T> implements MyList<T>{
private T[] list;
private int size=0;
private int index=0;
public MyArrayList() {
index=0;
size=0;
list=(T[]) new Object[100];//最大长度为100
}
@Override
public void addElement(T obj) {
list[this.index++]=obj;
size++;
}
@Override
public Object getElementAt(int index) {
return this.list[index];
}
@Override
public Iterator iterator() {
return new ConcreteIterator<T>(this);
}
@Override
public int getSize() {
return this.size;
}
}
class Student{
public String name;
public Student(String name) {
this.name=name;
}
public String getName() {
return this.name;
}
}
public class Client1 {
public static void main(String[] args) {
MyList<Student> myarraylist=new MyArrayList<Student>();
Student stu1=new Student("Tom");
Student stu2=new Student("Jack");
Student stu3=new Student("Ada");
Student stu4=new Student("Bob");
myarraylist.addElement(stu1);
myarraylist.addElement(stu2);
myarraylist.addElement(stu3);
myarraylist.addElement(stu4);
Iterator it=myarraylist.iterator();
while(it.hasNext()){
Student stu=(Student) it.next();//泛型
System.out.println(stu.getName());
}
}
}
输出结果
Tom
Jack
Ada
Bob