Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Avoid inserting duplicate in 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>();

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.

like image 946
user2766131 Avatar asked Sep 25 '13 19:09

user2766131


People also ask

Can we add duplicate items into an ArrayList?

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.

Does ArrayList allow duplicates in Java?

ArrayList allows duplicate values in its collection. On other hand duplicate elements are not allowed in Hashset.

Which data structure does not allow duplicates Java?

The underlying data structure for HashSet is Hashtable. As it implements the Set Interface, duplicate values are not allowed.


1 Answers

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.

like image 198
Mike Clark Avatar answered Oct 19 '22 16:10

Mike Clark