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?
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?
Off the top of my head, lists allow duplicates. You could quickly implement a
UniqueArrayList
and override all theadd
/insert
functions to check forcontains()
before you call the inherited methods. For personal use, you could only implement theadd
method you use, and override the others to throw an exception in case future programmers try to use the list in a different manner.There's no Java collection in the standard library to do this.
LinkedHashSet<E>
preserves ordering similarly to aList
, though, so if you wrap your set in aList
when you want to use it as aList
you'll get the semantics you want.Alternatively, the Commons Collections (or
commons-collections4
, for the generic version) has aList
which does what you want already:SetUniqueList
/SetUniqueList<E>
.So here's what I did eventually. I hope this helps someone else.
The documentation for collection interfaces says:
So if you don't want duplicates, you probably shouldn't use a list.
in
add
method, why not usingHashSet.add()
to check duplicates instead ofHashSet.consist()
.HashSet.add()
will returntrue
if no duplicate andfalse
otherwise.Here is what I did and it works.
Assuming I have an
ArrayList
to work with the first thing I did was created a newLinkedHashMap
.Then I attempt to add my new element to the
LinkedHashSet
. The add method does not alter theLinkedHasSet
and returns false if the new element is a duplicate. So this becomes a condition I can test before adding to theArrayList
.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 withaddAll
by looping through the elements and calling the add method.