java:我们对Iterator理解错了

Iterator是解决不同容器的一种设计模型,同时支持ArrayList、LinkedList、HashSet、TreeSet集合数据的迭代。


java:我们对Iterator理解错了_第1张图片
image.png

import typeinfo.pets.;
import java.util.
;
public class CrossContainerIteration {
public static void display(Iterator it) {
while(it.hasNext()) {
Pet p = it.next();
System.out.print(p.id() + ":" + p + " ");
}
System.out.println();
}
public static void main(String[] args) {
ArrayList pets = Pets.arrayList(8);
LinkedList petsLL = new LinkedList(pets);
HashSet petsHS = new HashSet(pets);
TreeSet petsTS = new TreeSet(pets);
display(pets.iterator());
display(petsLL.iterator());
display(petsHS.iterator());
display(petsTS.iterator());
}
}
/* 输出
0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug 7:Manx
0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug 7:Manx
4:Pug 6:Pug 3:Mutt 1:Manx 5:Cymric 7:Manx 2:Cymric 0:Rat
5:Cymric 2:Cymric 7:Manx 1:Manx 3:Mutt 6:Pug 4:Pug 0:Rat

还可以与for循环联合使用

List all = new ArrayList(Arrays.asList(insarray));
all.addAll(alist);
Iterator it = all.iterator();
for(int i=0;i String outstr = it.next();
it.remove();
System.out.print(outstr);
}

你可能感兴趣的:(java:我们对Iterator理解错了)