Search code examples
javajava-8technical-debt

class inherits unrelated defaults for spliterator() from types java.util.Set and java.util.List


I have class that implements Set and List. Programs works fine in Java6 and Java7

public class SetList<V> implements Set<V>, List<V>
{
  ....
}

With Java 8 , this does not compile. Error is

java: class trials.SetList inherits unrelated defaults for spliterator() from types java.util.Set and java.util.List

java/util/Set.java:394

 ...
@Override
default Spliterator<E> spliterator() {
    return Spliterators.spliterator(this, Spliterator.DISTINCT);
}

java/util/List.java

...
@Override
default Spliterator<E> spliterator() {
    return Spliterators.spliterator(this, Spliterator.ORDERED);
}

Does it mean I cannot have class that implement both Set and List in Java 8? (It looks like time has come to pay our technical debts.)


Solution

  • While it is unusual that a class implements both List and Set, there are some situations, where a Set can also support being a somewhat limited List.

    Personally, I prefer to declare an asList() method in these cases, instead of implementing both List and Set at the same time. Something like this:

    public class SetList<V> implements Set<V> {
        public List<V> asList(){
            // return a list representation of this Set
        }
    }
    

    On the other hand, if you already have an existing class, that implements both List and Set, then the simplest solution for your problem is perhaps to explicitly call one of the super spliterator()methods:

    public class SetList<V> implements Set<V>, List<V> {
        @Override
        public Spliterator<V> spliterator() {
            return List.super.spliterator();
        }
    }