Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List implementation that is both a Set a List (sequence)?

I'm in the position of extending LinkedList and implement Set, so that I have a list with no duplicates. I'm wondering if such an implementation doesn't exist already?

All I'm planning to do is to override the add(e) method to first look-up the element, and if present don't add it. Something like:

add(E){
   if(get(E) == null) super.add(E);
}
like image 268
simpatico Avatar asked Oct 13 '10 02:10

simpatico


2 Answers

No Java implementation exists in the standard collections.

However, you can take a look at SetUniqueList from the Common Collections which may be along the lines of what you are looking for.

like image 179
Anthony Forloney Avatar answered Oct 15 '22 22:10

Anthony Forloney


Maybe LinkedHashSet does what you want. It keeps elements in (by default) insertion order.

It is not possible to implement both interfaces at the same time (at least if you want to follow the specifications for List and Set), because the hashCode definitions conflict.

Returns the hash code value for this list. The hash code of a list is defined to be the result of the following calculation:

hashCode = 1;
  Iterator i = list.iterator();
  while (i.hasNext()) {
      Object obj = i.next();
      hashCode = 31*hashCode + (obj==null ? 0 : obj.hashCode());
  }

versus

Returns the hash code value for this set. The hash code of a set is defined to be the sum of the hash codes of the elements in the set, where the hashcode of a null element is defined to be zero. This ensures that s1.equals(s2) implies that s1.hashCode()==s2.hashCode() for any two sets s1 and s2, as required by the general contract of the Object.hashCode method.

like image 37
Thilo Avatar answered Oct 15 '22 22:10

Thilo