返回java中iterator()方法的类型 [英] Return type of iterator() method in java

查看:357
本文介绍了返回java中iterator()方法的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java的新朋友和学习的过程。
我需要一个有效理论支持的问题的答案。
考虑以下行 -

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-

Iterator itr = al.iterator(); 

其中 是ArrayList(类)类型的一些集合对象。
我想知道这里的返回类型

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

它不一定是原始数据类型,那么它可以是对象,但是因为每个对象属于一个类,所以它是哪个类。文档和书籍等说它有返回类型的迭代器。但 是一个接口。另一方面,我们说一个接口不能有一个直接的对象。虽然接口变量可以引用实现它的类的一个对象。

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 Iterator is 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.

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

So the above syntax is correct (as Iterator variable itr could be used to refer to an object of some class implementing it). But in realty it is object of which class? And can substituting itr with reference variable of that class will cause no error (I have tried substituting itr with 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.

推荐答案


我想知道这里的返回类型al.iterator )

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

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

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.

假设工作在ArrayList上的Java开发人员想将它们的迭代器实现重命名为ArrayListIterator,而不是它们现在调用它们。如果你的代码依赖于知道确切的Iterator实现,你必须改变你的代码只是为了处理你不应该看到的ArrayList内部的改变。

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.

这篇关于返回java中iterator()方法的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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