Search code examples
javagenericstreesetpecs

Java's TreeSet.add() does not follow the PECS principle issue (Generics)


I have the following piece of code:

public interface Segment<T> extends Period { ... };

public class SegmentImpl_v1<T> implements Segment<T> { ... };


public interface TimeLine<T, S extends Segment<T>> { ... };

public class TimeLineImpl<T, S extends Segment<T>>
        implements TimeLine<T, S> {

    private SortedSet<S> segments = new TreeSet<S>();

    public void someFunction() {

        // no suitable method for...
        segments.add(new SegmentImpl_v1<T>(...)); 

    }

}

and I get a no suitable method for... when adding a segment instance. It seems like Java's treeset does not apply the PECS principle. Is there a solution to this issue?

SOLUTION

I implemented:

public static <T> Segment<T> newItem(Period p, T itemValue) {
    return new SegmentImpl_v1(p, itemValue);
}

in SegmentImpl_v1 and call it in someFunction().


Solution

  • PECS has nothing to do with this. (You don't have any bounded wildcards.)

    The problem is SegmentImpl_v1<T> is not a subtype of S. When you pass an argument to a method it must be a subtype of the declared type of the parameter.