Java:避免在数组列表中插入重复项

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

Java: Avoid inserting duplicate in arraylist

javadata-structures

提问by user2766131

I am novice to java. I have an ArrayListand I want to avoid duplicates on insertion. My ArrayListis

我是java新手。我有一个ArrayList,我想避免插入重复。我的ArrayList

ArrayList<kar> karList = new ArrayList<kar>();

and the the field I want to check is :

我要检查的字段是:

 kar.getinsertkar().

I have read that I can use HashSetor HashMapbut I have no clue.

我读过我可以使用HashSetHashMap但我不知道。

回答by blackpanther

Use a HashSetinstead of an ArrayList. But, to really make the HashSetreally work well, you must override the equals()and hashCode()methods of the class/objects that are inserted into the HashSet.

使用 aHashSet而不是ArrayList。但是,要真正使HashSet真正的工作很好,你必须覆盖equals()hashCode()被插入类/对象的方法HashSet

Foe example:

敌例:

 Set<MyObject> set = new HashSet<MyObject>();
 set.add(foo);
 set.add(bar);

 public class MyObject {
     @Override
     public boolean equals(Object obj) {
         if (obj instanceof MyObject)
             return (this.id = obj.id) 
         else
             return false;
     }
     // now override hashCode()
}

Please see the following documentationfor overriding hashCode()and equals().

请参阅以下文档以覆盖hashCode()equals()

回答by Mike Clark

Whenever you want to prevent duplicates, you want to use a Set.

每当您想防止重复时,您都想使用Set.

In this case, a HashSet would be just fine for you.

在这种情况下,HashSet 对你来说就足够了。

HashSet karSet = new HashSet();
karSet.add(foo);
karSet.add(bar);
karSet.add(foo);
System.out.println(karSet.size());
//Output is 2

For completeness, I would also suggest you use the generic (parameterized) version of the class, assuming Java 5 or higher.

为了完整起见,我还建议您使用类的通用(参数化)版本,假设 Java 5 或更高版本。

HashSet<String> stringSet = new HashSet<String>();
HashSet<Integer> intSet = new HashSet<Integer>();
...etc...

This will give you some type safety as well for getting items in and out of your set.

这将为您提供一些类型安全以及将项目放入和取出您的集合。

回答by Kent

You can use LinkedHashSet, to avoid duplicated elements and keep the insertion order.

您可以使用LinkedHashSet, 来避免重复元素并保持插入顺序。

http://docs.oracle.com/javase/7/docs/api/java/util/LinkedHashSet.html

http://docs.oracle.com/javase/7/docs/api/java/util/LinkedHashSet.html

回答by r0t0xd

A set is simply a collection that can contain no duplicates so it sounds perfect for you.

集合只是一个不能包含重复项的集合,因此听起来很适合您。

It is also very simple to implement. For example:

实现起来也非常简单。例如:

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

This would provide you a set that can hold Objects of type String.

这将为您提供一个可以容纳 String 类型对象的集合。

To add to the set is just as simple:

添加到集合同样简单:

mySet.add("My first entry!");

By definition of a set, you can add whatever you want and never run into a duplicate.

根据集合的定义,您可以添加任何您想要的东西,并且永远不会遇到重复的情况。

Have fun!

玩得开心!

EDIT :If you decide you are dead-set on using an ArrayList, it is simple to see if an object is already in the list before adding it. For example:

编辑:如果您决定使用 ArrayList,则很容易在添加对象之前查看该对象是否已在列表中。例如:

public void addToList(String newEntry){
    if(!myList.contains(newEntry))
        myList.add(newEntry);
}

Note: All my examples assume you are using String objects but they can easily be swapped to any other Object type.

注意:我的所有示例都假设您使用的是 String 对象,但它们可以轻松交换为任何其他 Object 类型。

回答by Sajan Chandran

You need to use any Setimplementation, e.g you can use HashSet. If you want to addcustom object karinto your HashSet, you need to overrideequalsand hashcodemethod. You can read more about equalsand hashcode, see

您需要使用任何Set实现,例如您可以使用HashSet. 如果你想add自定义对象kar到你的HashSet,你需要overrideequalshashcode方法。您可以阅读更多关于equalsand 的信息hashcode请参阅

回答by Danail Tsvetanov

You can implement own List which extends LinkedList and override its add methods:

您可以实现自己的 List 扩展 LinkedList 并覆盖其添加方法:

  1. public boolean add(E e)
  2. public void add(int index, E element)
  3. public boolean addAll(Collection collection)
  4. public boolean addAll(int index, Collection collection)
  1. 公共布尔添加(E e)
  2. public void add(int index, E 元素)
  3. public boolean addAll(集合集合)
  4. public boolean addAll(int index, Collection collection)