为什么Linkedlist的add
方法在Java中返回true?
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/LinkedList.html#add(E)
为什么不把它变成一种无效的方法呢?我知道它写着“根据Collection.add的一般契约”,但是为什么这个契约/接口不使add
成为一个无效的方法呢?
发布于 2012-05-07 21:55:11
这是为了允许以列表或集合的形式引用LinkedList实例。
boolean addSomething(Collection c) {
return c.add(null); // expects collection, with add returning boolean
}
void hackList(LinkedList list) {
addSomething(list); // list is a Collection, OK to pass
}
LinkedList 是一个列表和集合。
至于集合为什么需要返回布尔值,这在各自的javadocs中看上去很清楚:
此集合包含指定元素的...Ensures (可选操作)。如果由于调用而更改此集合,则返回
true
。(如果此集合不允许重复且已经包含指定的元素,则返回false
。).
发布于 2012-05-07 23:54:48
除了给出最好的回答外,知道您只是尝试将null
添加到列表中,因此没有更改它,这是很有用的。虽然你可以单独检查一下,但能说出
if (myList.add(foo)) { doSomething(); }
或者也许
while (myList.add(buffer.readLine()));
https://softwareengineering.stackexchange.com/questions/147669
复制相似问题