Page 1 of 1

About Question com.enthuware.ets.scjp.v6.2.100 :

Posted: Wed Oct 08, 2014 11:37 am
by piotrkmiotczyk
Hi. I'm being linked here from:
The signature of a method in a class is as follows:

public static <E extends CharSequence> List<? super E> doIt(List<E> nums)

This method is being called in the following code:

result = doIt(in);

Given that String implements CharSequence interface, what should be the reference type of 'in' and 'result' variables?

Answer:
ArrayList<String> in;
List result;
-------------------
I'm having trouble with this. If method returns <? super E> why does it not fit into Object type variable?
What's the difference between this and getting something out of Collection<? super E> and into Object variable?

Re: About Question com.enthuware.ets.scjp.v6.2.100 :

Posted: Wed Oct 08, 2014 12:08 pm
by admin
The issue is that the object returned by doIt method would be a typed List. A typed list should only be allowed to store objects that belong to that type. But List<Object> can store any object. So if you assign the return value to List<Object>, you could circumvent the restriction on that List. The compiler prevents you from that by refusing to assign a typed list to List<Object>.

HTH,
Paul.

Re: About Question com.enthuware.ets.scjp.v6.2.100 :

Posted: Thu Oct 09, 2014 5:56 am
by piotrkmiotczyk
Thanks.

Re: About Question com.enthuware.ets.scjp.v6.2.100 :

Posted: Mon Nov 13, 2023 8:42 am
by Tester
if I write:
public static <E extends CharSequence> List<? super E> doIt(List<E> nums) {
return nums;
}
and to run it:
List<CharSequence> in = new ArrayList<>();
var res = doIt(in);
It looks ok. Does it mean that the answer:
List<CharSequence> in;
List<CharSequence> result;
is also right?

Re: About Question com.enthuware.ets.scjp.v6.2.100 :

Posted: Mon Nov 13, 2023 9:31 am
by admin
No, if you use List<CharSequence> in; and List<CharSequence> result; the code won't compile. So it is not a right answer.
If you declare res as var, that means the compiler will infer the type for you. But the question is asking you to specify the type. var is not a type.