java中iterator()方法的返回类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23038578/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 20:13:24  来源:igfitidea点击:

Return type of iterator() method in java

javamethodscollectionsiteratorreturn-type

提问by user3528086

I am a new-comer in Java and in process of learning. I need a an answer of following question supported with valid theory. Consider the following line-

我是Java新手,正在学习中。我需要一个由有效理论支持的以下问题的答案。考虑以下行-

Iterator itr = al.iterator(); 

where alis some collection object of ArrayList (class) type. I want to know what is here the return type of

其中al是 ArrayList(类)类型的某个集合对象。我想知道这里的返回类型是什么

al.iterator()

al.iterator()

It is not definitely of a primitive data type, then it could be an object, but since every object belong to a class then it is of which class. Documentation and books etc says it has return type of Iterator. But Iteratoris an interface. On other hand we say an interface could not have a direct object. Although interface variable could refer to an object of a class or classes that implements it.

它不是绝对的原始数据类型,那么它可以是一个object,但是由于每个对象都属于一个类,那么它属于哪个 class。文档和书籍等说它具有迭代器的返回类型。但是Iterator是一个接口。另一方面,我们说接口不能有直接对象。尽管接口变量可以引用一个或多个实现它的类的对象。

-

——

So the above syntax is correct (as Iterator variable itrcould be used to refer to an object of some class implementing it). But in realty it is object of which class? And can substituting itrwith reference variable of that class will cause no error (I have tried substituting itrwith ref. variable of ArrayList class in above line but that causes an error). I am using this syntax very often also in Generics form, but dont know the theory behind this. And I am supposing I am lacking a very basic concept here. Please rectify.

所以上面的语法是正确的(因为迭代器变量itr可用于引用实现它的某个类的对象)。但实际上它是哪个类的对象?并且可以用该类的引用变量替换itr不会导致错误(我曾尝试用上面行中的 ArrayList 类的引用变量替换itr但这会导致错误)。我也经常以泛型形式使用这种语法,但不知道这背后的理论。我假设我在这里缺乏一个非常基本的概念。请纠正。

回答by Braj

The implementation is defined in AbstractListitself. Find it at its source code.

实现AbstractList本身是定义的。在它的源代码中找到它。

public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {
    private class Itr implements Iterator<E> {
       ...
    }

    public Iterator<E> iterator() {
       return new Itr();
    }
}

Try

尝试

System.out.println(new ArrayList<String>().iterator().getClass().getName());

output

输出

java.util.AbstractList$Itr

回答by user2357112 supports Monica

I want to know what is here the return type of al.iterator()

我想知道 al.iterator() 的返回类型是什么

You shouldn't care. It doesn't matter what particular implementation of Iterator the method returns, only that it returns an Iterator. You can call next, hasNext, and remove, or iterate with a for-each loop, without knowing that it happens to be an ArrayList.Itr or whatever the implementation is.

你不应该在意。方法返回 Iterator 的具体实现并不重要,只要它返回一个 Iterator。您可以调用 next、hasNext 和 remove,或者使用 for-each 循环进行迭代,而无需知道它恰好是一个 ArrayList.Itr 或任何实现。

Suppose the Java developers working on the ArrayList want to rename their iterator implementation to ArrayListIterator instead of whatever they're calling it now. If your code relied on knowing the exact Iterator implementation, you would have to change your code just to handle an ArrayList-internal change you shouldn't even see.

假设处理 ArrayList 的 Java 开发人员想要将他们的迭代器实现重命名为 ArrayListIterator 而不是他们现在调用的任何名称。如果您的代码依赖于知道确切的 Iterator 实现,则您将不得不更改代码以处理您甚至不应该看到的 ArrayList 内部更改。

回答by Racereddy20

Iterator is generic and doesn't return a specific type unless you define it in the ArrayList. Iterator is an interface (part of the Java Collections) that returns the type that was passed to it. The Iterator is used to traverse the list of elements, and remove an element if necessary.

迭代器是泛型的,除非您在 ArrayList 中定义它,否则不会返回特定类型。迭代器是一个接口(Java 集合的一部分),它返回传递给它的类型。Iterator 用于遍历元素列表,并在必要时删除元素。

回答by Weishi Zeng

You are right saying that Iteratoris an interface. So, some class must implement this interface so you can use it.

你说得对,这Iterator是一个接口。因此,某些类必须实现此接口,以便您可以使用它。

The iterator interface defines what an iterator should do. In this case, the class ArrayList provides its own implementation of this interface.

迭代器接口定义了迭代器应该做什么。在这种情况下,类 ArrayList 提供了它自己的这个接口的实现。

What you get from al.iterator()is the inner class of ArrayList Itr(see following code, which IS iterator. (as we kind of describe the IS-A relationship)

你得到的al.iterator()是 ArrayList Itr的内部类(参见下面的代码,哪个是迭代器。(就像我们描述的 IS-A 关系)

(you can think of an inner class as a normal class for now. So the answer to your question is Itr, which is just a name, and all you should care about is its function, which is defined by interface Iterator.)

(您现在可以将内部类视为普通类。所以您的问题的答案是Itr,它只是一个名称,您应该关心的是它的功能,它由接口 Iterator 定义。)

   /**
     * An optimized version of AbstractList.Itr
     */
    private class Itr implements Iterator<E> {
        int cursor;       // index of next element to return
        int lastRet = -1; // index of last element returned; -1 if no such
        int expectedModCount = modCount;

        public boolean hasNext() {
            return cursor != size;
        }
       .....
  }

This code is by Josh Bloch and Neal Gafter, who wrote the ArrayList class.

这段代码是由 Josh Bloch 和 Neal Gafter 编写的,他们编写了 ArrayList 类。

回答by domih

You can define the return type of your Iterator beforehand. As you declare the iterator, you can (and should) define the type of your list items like this:

您可以预先定义迭代器的返回类型。在声明迭代器时,您可以(并且应该)像这样定义列表项的类型:

Iterator<File> itr = al.iterator();

Iterator<File> itr = al.iterator();

So when you access itryou don't have to cast to file, e.g. (File) itr.next()but can directly use it in your while loop:

因此,当您访问时,itr您不必强制转换为文件,例如,(File) itr.next()但可以直接在您的 while 循环中使用它:

while (it.hasNext()) { File f = itr.next() }

while (it.hasNext()) { File f = itr.next() }

Your compiler now won't complain when using next().

你的编译器现在在使用 next() 时不会抱怨了。

回答by Atul Sharma

Simply it returns the object it does iterate. For example you can refer to the code below.

它只是返回它迭代的对象。例如,您可以参考下面的代码。

    while(itr.hasNext())
    {
        String str = itr.next().toString(); // Converting an answer type object into String.
        System.out.println(str);
    }