16

我是java新手。我有一个ArrayList并且我想避免在插入时重复。我ArrayList的是

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

我要检查的字段是:

 kar.getinsertkar().

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

4

7 回答 7

27

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

在这种情况下,一个 HashSet 对你来说就很好了。

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

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

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

这将为您提供一些类型安全性以及将项目进出您的集合。

于 2013-09-25T19:47:06.530 回答
12

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

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

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

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

添加到集合中也很简单:

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

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

玩得开心!

编辑:如果您决定使用 ArrayList,那么在添加之前查看对象是否已经在列表中很简单。例如:

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

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

于 2013-09-25T19:48:09.257 回答
8

使用 aHashSet而不是ArrayList. 但是,要HashSet真正让.equals()hashCode()HashSet

敌人示例:

 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()
}

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

于 2013-09-25T19:45:14.500 回答
6

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

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

于 2013-09-25T19:47:40.807 回答
0

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

于 2013-09-25T19:50:42.397 回答
0

删除 ArrayList 中重复字符串的示例:

var list = new ArrayList<>(List.of(
        "hello",
        "java",
        "test",
        "hello"
));

System.out.println(list);

System.out.println(new ArrayList<>(new HashSet<>(list)));

输出:

[hello, java, test, hello]
[java, test, hello]
于 2022-01-02T17:39:16.350 回答
0

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

  1. 公共布尔加法(E e)
  2. 公共无效添加(int索引,E元素)
  3. public boolean addAll(集合集合)
  4. public boolean addAll(int index, Collection 集合)
于 2018-03-28T14:26:56.017 回答