当 java 中链表的布尔 add(E 元素) 方法返回 false



当java中链表的布尔add(E元素(方法返回false时?

我调查了 LinkedList 实现,发现布尔 add(E 元素( 等效于 void addLast(E 元素( 方法

唯一的区别是

addLast(E 元素( 方法实现:

void addLast(E e) {
Node<E> l = last;
Node<E> newNode = new Node<>(l, e, null);
last = newNode;
if (l == null)
first = newNode;
else
l.next = newNode;
size++;
}

和 add(E 元素( 方法实现:

boolean add(E e) {
addLast(e);
return true;
}

因为java.util.LinkedList实现了Collection接口,如果集合因操作而更改,则该接口中的add()方法应返回 true。对于链表,这始终是正确的。

下面是一个add()返回 false 的示例:

Set<Integer> set = new HashSet<>();
System.out.println(set.add(1));
System.out.println(set.add(2));
System.out.println(set.add(1));

输出:

true
true
false

第三个add返回 false,仅仅是因为集合没有因为操作而更改(它已经包含 1(。

它总是返回 true。它必须返回布尔值,因为它实现的接口(java.util.List(强制它返回布尔值。

/**
* Appends the specified element to the end of this list.
*
* <p>This method is equivalent to {@link #addLast}.
*
* @param e element to be appended to this list
* @return {@code true} (as specified by {@link Collection#add})
*/
public boolean add(E e) {
linkLast(e);
return true;
}

但是,java.util.Set有不同的行为。它仅在没有相同元素时才添加元素(根据Object.equals()(。就像@jrook提到的,如果您添加的元素已经存在,它将返回 false。