阅读 Bruce Eckel 的 Java 哲学,第 338 页
作为另一个例子,考虑创建一个独立于容器的显示方法:
//: holding/CrossContainerIteration.java import typeinfo.pets.*j import java.util.*j public class CrossContainerIteration { public static void display(Iterator<Pet> it) { while(it.hasNext()) { Pet p = it.next(); System.out.print(p.id() + ":" + p + " "); } System.out.println(); } public static void main(String[] args) { ArrayList<Pet> pets = Pets.arrayList(8); LinkedList<Pet> petsLL = new LinkedList<Pet>(pets); HashSet<Pet> petsHS = new HashSet<Pet>(pets); TreeSet<Pet> petsTS = new TreeSet<Pet>(pets); display(pets.iterator()); display(petsLL.iterator()); display(petsHS.iterator()); display(petsTS.iterator()); } } /* Output: 0:Rat l:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug 7:Manx 0:Rat l:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug 7:Manx 4:Pug 6:Pug 3:Mutt l:Manx 5:Cymric 7:Manx 2:Cymric 0:Rat 5:Cymric 2:Cymric 7:Manx l:Manx 3:Mutt 6:Pug 4:Pug 0:Rat *///:~请注意,display() 方法不包含有关序列类型的信息。
为什么作者说它display不包含有关序列类型的信息,因为类型是在传入方法参数本身中指定的display(Iterator<Pet> it)?是的,并且在方法内部指示Pet p
在 Eckel 中,这些概念是同义词:
List它也称为序列容器:和顺序:
资料来源:Bruce Eckel,《Java 思考第 4 版》,2007 年 12 月
在此示例中,类型化迭代器
Iterator<Pet>允许您从容器/集合类型(Set / List)和这些容器/序列类型(HashSet / TreeSet或ArrayList / LinkedList)的具体实现中进行抽象。