Java:避免在arraylist中插入重复 [英] Java: Avoid inserting duplicate in arraylist
本文介绍了Java:避免在arraylist中插入重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
ArrayList
,我想避免重复插入。我的 ArrayList
是 ArrayList< kar> karList = new ArrayList< kar>();
,我想检查的字段是:
kar.getinsertkar()。
我看过我可以使用 HashSet
或 HashMap
,但我没有线索。
解决方案
每当你想您可以使用 Set
。
在这种情况下,一个HashSet对你而言会很好。
HashSet karSet = new HashSet();
karSet.add(foo);
karSet.add(bar);
karSet.add(foo);
System.out.println(karSet.size());
//输出是2
为了完整,我还建议你使用generic参数化)版本的类,假定Java 5或更高版本。
HashSet< String> stringSet = new HashSet< String>();
HashSet< Integer> intSet = new HashSet< Integer>();
...等...
这将给你一些类型的安全,将项目进出您的集合。
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>();
and the the field I want to check is :
kar.getinsertkar().
I have read that I can use HashSet
or HashMap
but I have no clue.
解决方案
Whenever you want to prevent duplicates, you want to use a Set
.
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
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:避免在arraylist中插入重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文