Java: Avoid inserting duplicate in arraylist

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.

Leave a Comment