Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a no-duplicate List implementation out there?

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?

like image 607
Yuval Avatar asked Nov 06 '08 13:11

Yuval


People also ask

Which list will not allow duplicates?

Duplicates : ArrayList allows duplicate values while HashSet doesn't allow duplicates values.

Why Set doesn't allow duplicates what is its internal implementation?

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.

Does HashSet allow duplicates?

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.


2 Answers

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>.

like image 69
Calum Avatar answered Sep 29 '22 00:09

Calum


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.

like image 32
user3570018 Avatar answered Sep 28 '22 23:09

user3570018