Home > Software design >  What difference between <T extends Foo> and <? extends Foo>?
What difference between <T extends Foo> and <? extends Foo>?

Time:11-24

I have following code:

abstract public class Base {
    private static final HashMap<Integer, ? extends Base> hashMap = new HashMap<>();

    public static <T extends Base> void put(Integer key, T val) {
        hashMap.put(key, val);
    }

    public static <T extends Base> T get(Integer key) {
        return hashMap.get(key);
    }
}

So, i got incompatible types at Base.put() method: <T extends Base> and <? extends Base>.

What difference and how to rewrite that code properly?

CodePudding user response:

Quite simple:

? - is a wildcard

T - is a generic type

They are similar but different. If you want to enforce the type,them you cannot use a wildcard. You have to use generics

Example

public <T extends Number> void copy(List<T> dest,List<T> src){
    //code
}

The code above will be able to copy a list from src, to dest. Both src and dest have the same generic type, so it is safe to copy each element.

public void copy(List<? extends Number> dest, List<? extends Number> src){
    //code
}

The code above is not very good. dest could be of type List<Integer> while src could be of type List<Double>

I hope this helps

  • Related