Teste MasterExam - Generics [RESOLVIDO]

2 respostas
CintiaDR

Given:

import java.util.*;
public class BackLister {
       //INSERT  HERE
	{
		List<T> output = new LinkedList<T>();
		for (T t : input){
			output.add(0, t);
		}
		return output; 
	}
}
Which of the following can be inserted at //INSERT HERE to compile and run without error? (selecionar todas as corretas)

a) public static <T> List<T> backwards(List<T> input)

b) public static <T> List<T> backwards(List<? extends T> input)

c) public static <T> List<T> backwards(List<? super T> input)

d) public static <T> List<? extends T> backwards(List<T> input)

e) public static <T> List<? super T> backwards(List<T> input)

f) public static <? extends T> List<T> backwards(List<T> input)

g) public static <?super T> List<T> backwards(List<T> input)

Explanation:
A, B, D and E are correct declarations
C is wrong because if the input can contain any subtype of T (such as Object), those elements can’t be added to an output list of type T. F and G are wrong because you can’t use wildcards in the type variable declaration.


Ok, A , B, C, F e G eu entendi perfeitamente. Minha dúvida são as letras D e E. Eu não entendi quando podemos usar coringa no RETORNO de uma função. Fora que, no enunciado diz que o troço tem que rodar sem erros, como raios chamaríamos a função???

public static void main(String[] args) {
    List&lt;String&gt; l = backwards(new ArrayList&lt;String&gt;());  
}

Isso dá o seguinte erro de compilação se tentamos as opções D ou E:
Type mismatch: cannot convert from List<capture#1-of ? super(ou extends) String> to List<String>

O que afinal é um erro fácil de explicar, já que um List<String> não pode receber um List<Object> nem o contrário.

Tá, qual é a mágica para fazer as opções D e E “run without error”?

2 Respostas

B

Por exemplo:

CintiaDR

:shock:

Funciona mesmo. Não sei para que eu quereria isso, mas funciona.

List&lt;String&gt; strs = Arrays.asList(new String[]{"boo", "far"});;
List&lt;? super String&gt; l = backwards(strs);   //List&lt;? extends String&gt; se for extends
for (Object o : l){
	System.out.println(o);
}

Obrigada.

Criado 16 de junho de 2009
Ultima resposta 16 de jun. de 2009
Respostas 2
Participantes 2