View Full Version : [JAVA] Generics wildcards
Ciao a tutti,
Neanche dal tutorial Oracle mi è chiaro, come mai non posso fare questo?
class NaturalNumber {
private int i;
public NaturalNumber(int i) {
this.i=i;
}
}
public class AnotherNaturalNumber extends NaturalNumber {
public AnotherNaturalNumber(int i) {
super(i);
}
public static void main(String[] args) {
List<AnotherNaturalNumber> le = new ArrayList<>();
List<? extends NaturalNumber> ln = le;
ln.add(new AnotherNaturalNumber (35)); // compile-time error
}
}
Grazie
Ciao a tutti,
Neanche dal tutorial Oracle mi è chiaro, come mai non posso fare questo?
class NaturalNumber {
private int i;
public NaturalNumber(int i) {
this.i=i;
}
}
public class AnotherNaturalNumber extends NaturalNumber {
public AnotherNaturalNumber(int i) {
super(i);
}
public static void main(String[] args) {
List<AnotherNaturalNumber> le = new ArrayList<>();
List<? extends NaturalNumber> ln = le;
ln.add(new AnotherNaturalNumber (35)); // compile-time error
}
}
Grazie
Vado a memoria. Attraverso una referenza con generico wildcard (che abbia limite superiore o inferiore non ha importanza) non puoi modificare l'oggetto. In qualche modo si può dire che è read-only.
le.add(...);
Questo invece funziona
banryu79
14-09-2012, 13:42
Qua trovi tutte le spiegazioni del caso:
http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html#Wildcard%20Instantiations
Avevo capito che l'oggetto era read-only (:D), la mia domanda era: come mai?
Risposta trovata nel link di banryu79:
In this situation the compiler does not let us assign anything to the field or pass anything to the put method. The reason is that the compiler cannot make sure that the object that we are trying to pass as an argument to a method is of the expected type, since the expected type is unknown. Similarly, the compiler does not know of which type the field is and cannot check whether we are assigning an object of the correct type, because the correct type is not known.
Per questo non permette di modificare l'oggetto, credo
vBulletin® v3.6.4, Copyright ©2000-2025, Jelsoft Enterprises Ltd.