Create an ArrayList of unique values

Create an Arraylist of unique values

You could use Set.toArray() method.

A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction.

http://docs.oracle.com/javase/6/docs/api/java/util/Set.html


Try checking for duplicates with a .contains() method on the ArrayList, before adding a new element.

It would look something like this

   if(!list.contains(data))
       list.add(data);

That should prevent duplicates in the list, as well as not mess up the order of elements, like people seem to look for.

Tags:

Java

Arraylist