我想不出一个更好的名字来描述这个问题,但我希望一个例子能让这个问题变得更简单.
假设我创建了自己的定制List
(它做什么并不重要):
static class MyList<E> extends AbstractList<E> {
@Override
public E get(int index) {
return null;
}
@Override
public int size() {
return 0;
}
}
我现在可以创建它的一个实例,并调用与我所覆盖的方法不同的方法:
MyList<String> myList = new MyList<>();
myList.iterator();
当然,iterator
should使用我声明的get
方法,但这是保证吗?这是否意味着iterator
不能以一种它根本不使用get
的方式改变?
举个更简单的例子,你可以考虑addAll
个.假设我的MyList
也覆盖了add
:
@Override
public boolean add(E e) {
return super.add(e); // irrelevant what it does
}
然后我可以做到:myList.addAll(someOtherCollection)
.addAll
could可以简单地实施:
for(E e: someOtherCollection) {
// use add that I have overridden
}
但与此同时,实现可以改变,根本不使用循环(例如ArrayList
).
诚然,iterator
和addAll
在文档中都提到了一些内容,例如:
该实现返回迭代器接口的直接实现,依赖于支持列表的Size()、Get(Int)和Remove(Int)方法.
和
This implementation iterates over the specified collection, 和 adds each object returned by the iterator to this collection, in turn.
So does that mean that this can NOT change 和 is treated as "specification"? Now that I wrote this long question 和 re-read it, the answer might be an obvious "yes".