Kev*_*vin 2 java collections iterator
什么是迭代器和集合?这两个有关系吗?
// the interface definition
Interface Iterator {
boolean hasNext();
Object next(); // note "one-way" traffic
void remove();
}
// an example
public static void main (String[] args){
ArrayList cars = new ArrayList();
for (int i = 0; i < 12; i++)
cars.add (new Car());
Iterator it = cats.iterator();
while (it.hasNext())
System.out.println ((Car)it.next());
}
Run Code Online (Sandbox Code Playgroud)
Interface Iterator是否单独预定义了这些方法名称或用户定义了哪些方法名称?下面这四行实际上讲的是什么?
cars.add (new Car());
Iterator it = cats.iterator();
while (it.hasNext())
System.out.println ((Car)it.next());
Run Code Online (Sandbox Code Playgroud)
谢谢.我正在阅读一本收藏的书.
正如其名称所示,Java集合是事物的集合.如果您不知道该单词,请在字典中查找.
收藏品种类很多.以集合的数学概念为例.你可以在一个集合中放置任意东西,但它永远不会包含同一个东西.集合中的东西不是有序的,也就是说你不能说A出现在B之前.另一种类型的集合是列表.列表可以多次包含相同的内容,列表中的内容顺序很重要.
所有这些集合的共同点是它们包含的东西,在Java中称为元素.当你想知道某个集合中的哪些东西时,你会遍历集合,这只是遍历所有元素的另一个术语.这就是它的Iterator作用.它基本上从集合的开头开始,你总是可以询问是否有下一个元素(hasNext()),如果存在,你可以访问该元素(next()),直到你迭代了集合中的所有元素.
| 归档时间: |
|
| 查看次数: |
13857 次 |
| 最近记录: |