仅当对象不存在时才将对象添加到 Java 结构中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18727655/
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-12 10:31:34  来源:igfitidea点击:

Add an object to a java structure only if it isn't already there

javaarraylist

提问by user2076476

I have an arrayList that I want to add to, as long as the value isn't already stored in it. For example if my array is like this:

我有一个要添加到的 arrayList,只要该值尚未存储在其中即可。例如,如果我的数组是这样的:

H
LK
KL
LS

And I have the value LS, it wouldn't be added. But if the value was A, it would be. I don't care about order or sorting. Just whether or not the information is in there.

我有价值 LS,它不会被添加。但如果值是 A,那就是 A。我不在乎顺序或排序。无论信息是否在那里。

I was thinking that the code should look something like this:

我在想代码应该是这样的:

value = A;
no = 0; 
for (int o; arraylist.length; o++)
   if (arraylist.get(o).equals(value)){
     continue;
   }else{ 
      no++;
   }
}
if (arraylist.length = no){
    arraylist.add(value);
}

But there has to be an easier way to do it. Does anyone know a more concise way to do this?

但必须有一种更简单的方法来做到这一点。有谁知道更简洁的方法来做到这一点?

采纳答案by Kon

I would consider using a Setinstead of an ArrayList. Sets are defined by their requirement that all objects be unique. A HashSetis a good default choice and might be the more correct data structure for you to use in this case, but that is ultimately your call.

我会考虑使用 aSet而不是 ArrayList。集合是由它们的要求定义的,即所有对象都是唯一的。AHashSet是一个很好的默认选择,可能是您在这种情况下使用的更正确的数据结构,但这最终是您的要求。

When you add to a set, the addmethod will return falseif the object is already contained in the set, and a duplicate will not be added.

添加到集合时,如果该对象已包含在集合中,则该add方法将返回false,并且不会添加重复项。

If you need predictable iteration order, you could use the LinkedHashSet.

如果您需要可预测的迭代顺序,您可以使用 LinkedHashSet。

This implementation differs from HashSet in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order)

此实现与 HashSet 的不同之处在于它维护一个双向链表,贯穿其所有条目。这个链表定义了迭代顺序,也就是元素被插入到集合中的顺序(插入顺序)

Finally, you could consider using a navigable set in TreeSet. It doesn't look sorting is important based on the information above, so it's probably not the right choice for you, but it's good information to have in your back pocket.

最后,您可以考虑在 TreeSet 中使用可导航集。根据上述信息,排序看起来并不重要,因此它可能不是您的正确选择,但将它放在您的后兜里是很好的信息。

Just make sure that if you are adding your own class's objects to a Set, that you override, and override properly, the equals() method. Not doing so will cause only references to be compared and will lead to unexpected behavior, and a notable headache. Use the @Override annotation to make sure you're overriding properly, but I digress.

只需确保如果您将自己的类的对象添加到 Set 中,请覆盖并正确覆盖 equals() 方法。不这样做只会导致只比较引用,并会导致意外行为和明显的头痛。使用 @Override 注释来确保您正确覆盖,但我离题了。

HashSet Javadocs

HashSet Javadocs

TreeSet Javadocs

树集 Javadocs

LinkedHashSet Javadocs

LinkedHashSet Javadocs

回答by nanofarad

Use ArrayList#containsinstead:

使用ArrayList#contains来代替:

if (!arraylist.contains(value)){
     arraylist.add(value);
}

Note that containsdepends on your objects having an equals()method. Namely, either the list contains null and valueis null, or value.equals(o)for some othat is an element of the list.

请注意,这contains取决于您的对象是否具有equals()方法。即,要么列表包含 null 并且value为 null,要么value.equals(o)对于某些o列表的元素。

回答by tmh

If you need Listsemantics (i.e. elements are ordered), then you could subclass ArrayList(you'd call it UniqueArrayListor something) and override its addmethod to call containsand add the element only if it doesn't exist.

如果您需要List语义(即元素是有序的),那么您可以子类化ArrayList(您可以调用它UniqueArrayList或其他东西)并覆盖其add方法以contains仅在元素不存在时调用和添加元素。

public class UniqueArrayList<E> extends ArrayList<E> {

    @Override
    public boolean add(E e) {
        if (!contains(e)) {
            return super.add(e);
        } else {
            return false;
        }
    }

    // TODO: override addAll etc.
}

This would be the most object-oriented way, compared to having if(!list.contains(...checks (or even loops) everywhere you need this.

if(!list.contains(...在需要的地方进行检查(甚至循环)相比,这将是最面向对象的方式。

It would also allow you to keep the existing functionality of the Listobjects, for instance accessing elements by index via get, in case this is a requirement.

它还允许您保留List对象的现有功能,例如通过索引访问元素get,以防万一。

If the concept of order is not important, you could use a Set. Sets, both by definition and implementation, contain only unique elements.

如果顺序的概念不重要,您可以使用Set. 集合,无论是定义还是实现,都只包含唯一的元素。

回答by darioo

One clean way to do it, if you don't mind the performance hit because of copying and ordering isn't important:

如果您不介意由于复制和排序而导致的性能下降,那么一种干净的方法并不重要:

Use a HashSet, insert everything in it and the copy its contents into a List. Example:

使用 a HashSet,插入其中的所有内容并将其内容复制到 a 中List。例子:

Set<String> set = new HashSet<String>();

set.add("H");
set.add("LK");
set.add("KL");
set.add("LS");
set.add("LS");
set.add("A");

List<String> list = new ArrayList<String>();
list.addAll(set);

System.out.println(list);

Output:

输出:

[A, KL, LK, LS, H]

回答by Marcin Szymczak

You probably have wrong data structure. Set will be better in this case.

你可能有错误的数据结构。在这种情况下设置会更好。