Java 为什么 List.add(E) 返回 boolean 而 List.Add(int, E) 返回 void?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24173117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 10:35:42  来源:igfitidea点击:

Why does List.add(E) return boolean while List.Add(int, E) returns void?

javacollectionsarraylist

提问by

Looking at the javadocI saw the that an ArrayList has an overloaded add method:

查看javadoc我看到一个 ArrayList 有一个重载的 add 方法:

public boolean add(E e)

Appends the specified element to the end of this list.

公共布尔添加(E e)

将指定的元素附加到此列表的末尾。

and

public void add(int index, E element)

Inserts the specified element at the specified position in this list. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).

public void add(int index, E 元素)

在此列表中的指定位置插入指定元素。将当前在该位置的元素(如果有)和任何后续元素向右移动(向它们的索引添加一个)。

I noticed that the first one returned a booleanwhile the second one was a void. As it turns out, the first addHAS to return a booleanbecause:

我注意到第一个返回了一段boolean时间,第二个是void. 事实证明,第一个add必须返回 aboolean因为:

Returns: true (as specified by Collection.add(E))

返回:true(由 Collection.add(E) 指定)

So I went to Collection.add(E):

所以我去了Collection.add(E)

boolean add(E e)

Ensures that this collection contains the specified element (optional operation). Returns true if this collection changed as a result of the call. (Returns false if this collection does not permit duplicates and already contains the specified element.)

布尔加法(E e)

确保此集合包含指定的元素(可选操作)。如果此集合因调用而更改,则返回 true。(如果此集合不允许重复并且已经包含指定的元素,则返回 false。)

So my question is, why is addspecified to return boolean instead of being a void? When I addsomething I would expect to only do an operation.

所以我的问题是,为什么add指定返回布尔值而不是空值?当我add做某事时,我希望只做一次手术。

I understand that there's other data structures that, as opposed to ArrayList, do not allow duplicates (such as sets). But even then, couldn't the problem be solved along the lines of:

我知道还有其他数据结构,与 ArrayList 不同,不允许重复(例如集合)。但即便如此,问题也不能按照以下方式解决:

public void add(E e){
    if(e is not in set){
        add e;
    }
}

That way if eIS in the set no action is taken. Why is it better to return a booleaninstead of the voidapproach?

这样,如果e是在集合中,则不采取任何行动。为什么返回 aboolean而不是void方法更好?

采纳答案by yshavit

Collection.addis a pretty generic method (not in the sense of Java generics -- in the sense of being widely applicable). As such, they wanted a return value that would apply generally.

Collection.add是一个非常通用的方法(不是在 Java 泛型的意义上——在广泛适用的意义上)。因此,他们想要一个普遍适用的返回值。

Some classes (like ArrayList) always accept elements, and so will always return true. You're right that in these cases, a return type of voidwould be just as good.

某些类(如ArrayList)始终接受元素,因此将始终返回true。你是对的,在这些情况下,返回类型void也一样好。

But others, like Set, will sometimes not allow an element to be added. In Set's case, this happens if an equal element was already present. It's often helpful to know that. Another example is a bounded collection (that can only hold a certain number of elements).

但其他人,例如Set,有时不允许添加元素。在Set's 的情况下,如果一个相等的元素已经存在,就会发生这种情况。知道这一点通常很有帮助。另一个例子是有界集合(只能容纳一定数量的元素)。

You could ask, "can't code just check this manually?" For instance, with a set:

你可能会问,“不能编码只是手动检查吗?” 例如,有一个集合:

if (!set.contains(item)) {
    set.add(item);
    itemWasAdded(item);
}

This is more verbose than what you can do now, but not a whole lot:

这比你现在可以做的更冗长,但不是很多:

if (set.add(item)) {
    itemWasAdded(item);
}

But this check-then-act behavior isn't thread safe, which can be crucial in multithreaded applications. For instance, it could be that another thread added an equal item between you checking set.contains(item)and the set.add(item)in the first code snippet. In a multithreaded scenario, those two actions really need to be a single, atomic action; returning booleanfrom the method makes that possible.

但是这种先检查后行动的行为不是线程安全的,这在多线程应用程序中可能是至关重要的。例如,可能是另一个线程在您检查set.contains(item)set.add(item)第一个代码片段中的之间添加了一个相等的项目。在多线程场景中,这两个操作确实需要是单个原子操作;boolean从方法返回使这成为可能。

回答by NimChimpsky

because it is often useful to know if something was actually added, or alternately was already there.

因为知道某些东西是否真的被添加了,或者已经在那里,这通常很有用。

回答by Hyman

Because it's an extra information which doesn't cost anything and can be useful in certain situations. For example:

因为这是一个额外的信息,不需要任何费用,并且在某些情况下很有用。例如:

Set<String> set = new HashSet<String>();
set.add("foobar");
boolean wasAlreadyThere = set.add("foobar");

Otherwise you would have to do

否则你将不得不做

boolean wasAlreadyThere = set.contains("foobar");
set.add("foobar");

which requires twice the work (first you have to lookup, then lookup again to add).

这需要两倍的工作(首先您必须查找,然后再次查找以添加)。