Java common field

I can't see my error and don't understand why it doesn't work. I have the following class:

public class Generic<K extends Comparable<K>> implements Comparable<Generic<K>> {
    // code

    public static List<Generic<String>> factory1(){...}
    public static List<Generic<Integer>> factory2(){...}

    private K mKey;

    @Override
    public int compareTo(NoteGroup<K> another) {
        return mKey.compareTo(another.mKey);
    }
}

      

In another class, I am not interested in the generic type and would like to use a wildcard like:

public class Anothter {
    private List<Generic<? extends Comparable>> mList;

    private void method1() {
        mList = Generic.factory1();
    }

    private void method2() {
        mList = Generic.factory2();
    }
}

      

But it doesn't work. The error message is that an extension of type Comparable is expected, not String / Integer.

Can I solve my problem? Why can't I compile the above code snippet?

Edit: Bug in methods method1 () and method2 (). I cannot assign the result to the factory methods for the mList field. The types are incompatible.

+3


source to share


2 answers


As one of the comments said - To make your code work, you need to change the following declaration in the Other class

private List<Generic<? extends Comparable>> mList;

      



to:

List<? extends Generic<?>> mList;

      

+1


source


private void method2() {
    mList = (List) Generic.factory2();
}

      



0


source







All Articles