Hello All,
I need help with the following two questions from K&B's book
1)public static <E extends Number> List<? super E> process(List<E> nums)
A programmer wants to use this method like this:
// INSERT DECLARATIONS HERE
output = process(input);
Which pairs of declarations could be placed at // INSERT DECLARATIONS HERE to allow the code to compile? (Choose all that apply.)
A.ArrayList<Integer> input = null;
ArrayList<Integer> output = null;
B. ArrayList<Integer> input = null;
List<Integer> output = null;
C. ArrayList<Integer> input = null;
List<Number> output = null;
D. List<Number> input = null;
ArrayList<Integer> output = null;
E. List<Number> input = null;
List<Number> output = null;
F. List<Integer> input = null;
List<Integer> output = null;
G. None of the above.
The correct answers are B,E,F and I chose B,C,E,F. Why C is not correct?I've been studying all day and My head hurts and I cant figure it out.
2)Given that
String implements java.lang.CharSequcnce, and:
import java.util.* ;
public class LongWordFinder {
public static void main(String [] args) {
String[] array = { "123", "12345678", "1", "12", "1234567890"};
List<String> list = Arrays.asList(array);
Collection<String> resultList = getLongWords(list);
}
// INSERT DECLARATION HERE
{
Collection<E> longWords = new ArrayList<E>();
for (E
word : coll)
if (word.length() > 6) longWords.add(word);
return longWords;
}
}
Which declarations could be inserted at // INSERT DECLARATION HERE so that the program will compile and run? (Choose all that apply.)
A. public static <E extends CharSequence> Collection<? extends CharSequence> getLongWords(Collection<E> coll)
B. public static <E extends CharSequence> List<E> getLongWords(Collection<E> coll)
C. public static Collection<E extends CharSequence> getLongWords(Collection<E> coll)
D. public static List<CharSequence> getLongWords(Collection<CharSequence> coll)
E. public static List<? extends CharSequence> getLongWords(Collection<? extends CharSequence> coll)
F. static public <E extends CharSequence> Collection<E> getLongWords(Collection<E> coll)
G. static public <E super CharSequence> Collection<E> getLongWords(Collection<E> coll)
G is wrong but I cant justify it. Could anyone kindly explain why G is wrong?
The answer to this one is F and I chose A,B.
The question here is that do we need to be specific about the return type i.e Collection<? extends CharSequence> is too vague. Do we have to specify the exact type to be returned incase of generics as in normal method declaration i.e int,String etc ?If this is the case, The method signature in question 1
public static <E extends Number> List<? super E> process(List<E> nums)
where the return type is List<? super E> is also vague. Then why is it correct?
I have a bad headache and I hope my questions are clear and not confusing.Waiting for a favorable reply.Thanks in advance.
Kind Regards,
Hasnain Javed Khan.