I know about SortedSet
, but in my case I need something that implements List
, and not Set
. So is there an implementation out there, in the API or elsewhere?
It shouldn't be hard to implement myself, but I figured why not ask people here first?
Duplicates : ArrayList allows duplicate values while HashSet doesn't allow duplicates values.
The meaning of "sets do not allow duplicate values" is that when you add a duplicate to a set, the duplicate is ignored, and the set remains unchanged. This does not lead to compile or runtime errors: duplicates are silently ignored.
Duplicates: HashSet doesn't allow duplicate values. HashMap stores key, value pairs and it does not allow duplicate keys. If the key is duplicate then the old key is replaced with the new value.
There's no Java collection in the standard library to do this. LinkedHashSet<E>
preserves ordering similarly to a List
, though, so if you wrap your set in a List
when you want to use it as a List
you'll get the semantics you want.
Alternatively, the Commons Collections (or commons-collections4
, for the generic version) has a List
which does what you want already: SetUniqueList
/ SetUniqueList<E>
.
Here is what I did and it works.
Assuming I have an ArrayList
to work with the first thing I did was created a new LinkedHashMap
.
LinkedHashSet<E> hashSet = new LinkedHashSet<E>()
Then I attempt to add my new element to the LinkedHashSet
. The add method does not alter the LinkedHasSet
and returns false if the new element is a duplicate. So this becomes a condition I can test before adding to the ArrayList
.
if (hashSet.add(E)) arrayList.add(E);
This is a simple and elegant way to prevent duplicates from being added to an array list. If you want you can encapsulate it in and override of the add method in a class that extends the ArrayList
. Just remember to deal with addAll
by looping through the elements and calling the add method.
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