问题描述
我是 Java 新手.我有一个 ArrayList
并且我想避免在插入时重复.我的 ArrayList
是
I am novice to java. I have an ArrayList
and I want to avoid duplicates on insertion. My ArrayList
is
ArrayList<kar> karList = new ArrayList<kar>();
我要检查的字段是:
kar.getinsertkar().
我已经读到我可以使用 HashSet
或 HashMap
但我不知道.
I have read that I can use HashSet
or HashMap
but I have no clue.
推荐答案
每当您想防止重复时,您都想使用 Set
.
Whenever you want to prevent duplicates, you want to use a Set
.
在这种情况下,HashSet 很适合您.
In this case, a HashSet would be just fine for you.
HashSet karSet = new HashSet();
karSet.add(foo);
karSet.add(bar);
karSet.add(foo);
System.out.println(karSet.size());
//Output is 2
为了完整起见,我还建议您使用类的通用(参数化)版本,假设是 Java 5 或更高版本.
For completeness, I would also suggest you use the generic (parameterized) version of the class, assuming Java 5 or higher.
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.
这篇关于Java:避免在数组列表中插入重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!