Java中的迭代器 [英] Iterator in Java

查看:132
本文介绍了Java中的迭代器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是迭代器和集合?
这两个有什么关系吗?

What is Iterator and collections? Does these two have any relations?

// 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());
}

Interface Iterator有没有单独预定义或用户定义的方法名?
下面这四行代表了什么?

Does the Interface Iterator has these method names alone predefined or its user defined?. What does these four lines below actually tell?

cars.add (new Car());
Iterator it = cats.iterator();
while (it.hasNext())
    System.out.println ((Car)it.next());

谢谢。我正在收集一本书。

Thanks. I am going through a book in collections.

推荐答案

Java集合就像名字一样,是集合的东西。如果你不知道这个词,可以在字典中查找。

The Java collections are, as the name says, collections of things. If you don't know that word, look it up in a dictionary.

有很多类型的集合。以一个集合的数学概念为例。你可以把任意的东西放在一个集合中,但它永远不会包含相同的东西不止一次。集合中的东西没有排序,也就是说你不能说 A在B 之前。另一种类型的集合是列表。列表可以多次包含相同的事物,列表中事物的顺序很重要。

There are many types of collections. Take for example the mathematical concept of a set. You can put arbitrary things in a set, but it will never contain the same thing more than once. The things in the set are not ordered, that is you cannot say A comes before B. Another type of collection is a list. A list can contain the same thing more than once, and the order of the things in the list is important.

所有这些集合的共同点是它们包含事物,在Java中称为元素。当您想知道某个集合中有哪些内容时,您可以遍历该集合,这只是用于所有元素的另一个术语。这是迭代器的作用。它基本上从一个集合的开头开始,你总是可以询问是否有下一个元素( hasNext()),如果有,你可以访问元素( next()),直到您遍历集合中的所有元素。

What all these collections have in common is that they contain things, which in Java are called elements. When you want to know which things are in a certain collection, you iterate over the collection, which is just another term for going through all elements. This is what an Iterator does. It basically starts at the beginning of a collection, you can always ask whether there is a next element (hasNext()), and if there is, you can get access to that element (next()), until you have iterated over all elements in the collection.

这篇关于Java中的迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆