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.
ArrayList allows duplicate values while HashSet doesn't allow duplicates values. Ordering : ArrayList maintains the order of the object in which they are inserted while HashSet is an unordered collection and doesn't maintain any order.
ArrayList allows duplicate values in its collection. On other hand duplicate elements are not allowed in Hashset.
The underlying data structure for HashSet is Hashtable. As it implements the Set Interface, duplicate values are not allowed.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With