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?
About Question com.enthuware.ets.scjp.v6.2.100 :
Moderator: admin
-
- Posts: 27
- Joined: Mon Sep 22, 2014 1:30 pm
- Contact:
-
- Site Admin
- Posts: 10078
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: About Question com.enthuware.ets.scjp.v6.2.100 :
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.
HTH,
Paul.
If you like our products and services, please help us by posting your review here.
-
- Posts: 27
- Joined: Mon Sep 22, 2014 1:30 pm
- Contact:
-
- Posts: 34
- Joined: Mon Oct 30, 2023 11:55 am
- Contact:
Re: About Question com.enthuware.ets.scjp.v6.2.100 :
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?
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?
-
- Site Admin
- Posts: 10078
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: About Question com.enthuware.ets.scjp.v6.2.100 :
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.
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.
If you like our products and services, please help us by posting your review here.
Who is online
Users browsing this forum: No registered users and 39 guests