I\'m trying to find an implementation of java.util.List
and java.util.Set
at the same time in Java. I want this class to allow only unique elements
You cannot implement List
and Set
at once without contract violation. See, for example, the Set.hashCode contract:
The hash code of a set is defined to be the sum of the hash codes of the elements in the set, where the hash code of a null element is defined to be zero.
On the other hand here's the contract of List.hashCode:
The hash code of a list is defined to be the result of the following calculation:
int hashCode = 1; for (E e : list) hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());
So it's impossible to implement single class which guarantees both contracts to be fulfilled. The same problem for equals
implementation.