Pavlo Boliak
Pavlo Boliak

Reputation: 83

interesting behaviour of upper bounded java wildcards

I have example:

public static <T extends Number> void doJob(List<T> pr,List<? extends Number> en,T tel){
            // 
            System.out.println(pr.get(0).intValue());

   }

List<? extends Integer> intList=new ArrayList<>();
Integer inval=200;
List<Integer> intList3=new ArrayList<Integer>(Arrays.asList(1,2,3));
doJob(intList3,intList,inval);//it is allowed 
intList=intList3;
doJob(intList,intList,intList.get(0));//IT IS FORBIDDEN

Why does compiler forbid call of doJob(intList,intList,intList.get(0)); even intList in fact is List type?

Upvotes: 3

Views: 43

Answers (1)

Jatin
Jatin

Reputation: 31724

Well that is because, Ultimately you are doing:

List<? extends Integer> ls = new ArrayList<Integer>();
doJob(ls,ls,ls.get(0));

So ls (or your intList) is actually a List of an unknown type. But what you do know, is that this unknown type extends Number.

So when you call doJob, T in doJob becomes this unknown type. Your second argument matches as List<? extends Number> is a super type to List<? extends Integer>.

As per your third argument, we already know that T is unknown and you try passing intList.get(0). Now intList.get will return ? extends Integer, i.e. another unknown type (which extends Integer). So you try passing an unknown type to a method which expects an unknown type. And two unknown's cant be guaranteed to be equal. Hence the error.

Upvotes: 3

Related Questions