黑马程序员技术交流社区
标题:
迭代器为啥不是new
[打印本页]
作者:
潘多拉
时间:
2014-9-4 16:51
标题:
迭代器为啥不是new
迭代器为啥不是new出来的呢?
作者:
java_dream
时间:
2014-9-4 17:10
这是因为创建对象的逻辑被iterator()方法封装了
作者:
刘亚东
时间:
2014-9-5 11:17
因为是创建集合后,调用iterator方法后返回的Iterator类型的对象才具备hasNext方法、next方法等,而这些方法所在的类是被封装在集合内部的,所以去除方式就可以直接访问集合内部元素。
作者:
yuZhe_toString
时间:
2014-9-5 12:17
额,因为那些集合实现了Iterator接口,由于数据结构不同,遍历的方式也不同,所以需要集合自定义变量方法,但是为了统一所以实现相同接口,以便于规范。
作者:
她只是过客
时间:
2014-9-6 18:24
好高深的回答
作者:
hsy
时间:
2014-9-6 22:05
我的理解是:其实它就是对象,只不过是被封装在iterator()方法中
作者:
天邃任我桓
时间:
2014-9-6 22:06
被封装了!
作者:
xpaibeyond
时间:
2014-9-8 01:31
具有迭代功能的集合是因为实现了Iterable接口, Iterable接口中只定义的一个返回值为Interator类型的iterator()方法, 实现Iterable接口的集合中覆写了iterator(),返回一个符合该集合数据结构的Iterator对象。
作者:
依然如故
时间:
2014-9-8 08:21
我也没看懂!!
作者:
李国荧
时间:
2014-9-8 08:53
以ArrayList为例,看一下它的源代码:
package java.util;
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
//这是从Collection接口继承得到的iterator方法
public Iterator<E> iterator() {
//下面的代码返回了一个Itr类的实例
return new Itr();
}
//私有内部类Itr,实现了Iterable接口
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;
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
}
复制代码
从上面代码可以看出,ArrayList的iterator方法返回的是一个内部类Itr的实例,该内部类实现了Iterator接口。
不仅仅是ArrayList,你可以从其他的集合类中找到类似的代码。
作者:
莫泊桑leon
时间:
2014-9-8 09:38
iterator的构造函数被私有化了,但调用iterator()函数可以返回一个Iterator类型的对象。这是单例设计的思想。
作者:
高鹏飞
时间:
2014-9-11 13:59
迭代器接口出现:将每一个容器中的取出方式进行了封装。并对外暴露。
这样无论是什么容器或者数据结构,只要内部取出方式实现了Iterator接口
都可以通过该接口取出这些容器中的元素
它的出现,将容器的取出方式和容器的数据结构相分离,降低了耦合性
而取出方式因为直接在访问容器中的元素,并依赖具体的数据结构,所以被定义在了容器中
通过内部类来实现Itertor接口
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2