views:

71

answers:

2

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);
}
+1  A: 

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.

Anthony Forloney
it's what I was looking for.Talking reuse and simplicity at the same time, would you recommend just creating my class, or importing this library from maven? Also, why doesn't it iherit from a standard list implementation?
simpatico
I would import this library, unless you feel the need to recreate this on your own, that choice is yours.
Anthony Forloney
@simpatico: You can upvote @Anthony's answer if you find it useful. :). Cheers!
JavaGeek
+4  A: 

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.

Thilo
LinkedHashSet does not behave like a true list because you cannot get, insert, update or delete positionally. And you could implement `equals` and `hashcode` in a hypothetical listset class so that they don't entirely obey the relevent interface / superclass contracts.
Stephen C
Yeah, that is why I said "maybe".
Thilo
it's what I've been using. However, I just noticed that when retrieving them from the DB with JPA2 they are not ordered. That's because I had the declaration as Set. I'll post another question about that.
simpatico
http://stackoverflow.com/questions/3920531/why-cannot-a-jpa-mapping-attribute-be-a-linkedhashset
simpatico