Kto może mi to wyjaśnić?Java Generics: dodanie niewłaściwego typu w kolekcji
mam te kilka klas:
abstract class Animal {
public void eat() {
System.out.println("Animal is eating");
}
}
class Dog extends Animal {
public void woof() {
System.out.println("woof");
}
}
class Cat extends Animal {
public void meow() {
System.out.println("meow");
}
}
I to jest akcja:
import java.util.ArrayList;
import java.util.List;
public class TestClass {
public static void main(String[] args) {
new TestClass().go();
}
public void go() {
List<Dog> animals = new ArrayList<Dog>();
animals.add(new Dog());
animals.add(new Dog());
doAction(animals);
}
public <T extends Animal> void doAction(List<T> animals) {
animals.add((T) new Cat()); // why is it possible?
// Variable **animals** is List<Dog>,
// it is wrong, that I can add a Cat!
for (Animal animal: animals) {
if (animal instanceof Cat) {
((Cat)animal).meow();
}
if (animal instanceof Dog) {
((Dog)animal).woof();
}
}
}
}
Ten przykład skompilować bez błędów, a wyjście jest:
woof
woof
meow
Ale jak czy mogę dodać na liście psa kota? A jak Cat jest rzucony na psa?
używam: java version "1.6.0_24". OpenJDK Runtime Environment (IcedTea6 1.11.1) (6b24-1.11.1-4ubuntu3)
Istnieją ostrzeżenia kompilatora, nie? –
Na pewno pojawi się ostrzeżenie kompilatora na animals.add ((T) new Cat()) ;. – tjg184
I tak zaczyna się szlak łez, czyli generics Java. –