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

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

where al is some collection object of ArrayList (class) type.

I want to know what is here the return type of

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

-

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.

解决方案

I want to know what is here the return type of 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.

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值