Is there an insertion order preserving Set that also implements List?

后端 未结 7 714
抹茶落季
抹茶落季 2020-12-01 03:50

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

7条回答
  •  一整个雨季
    2020-12-01 04:49

    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.

提交回复
热议问题