Created
September 19, 2014 17:43
-
-
Save koher/81c3d71a03c5caaed515 to your computer and use it in GitHub Desktop.
Javaで?を使わずにListがCovariantであるように振る舞わせると・・・
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import java.util.Arrays; | |
import java.util.List; | |
import static java.lang.System.out; | |
public class VarianceTest { | |
static class Animal { | |
} | |
static class Cat extends Animal { | |
} | |
public static void main(String[] args) { | |
List<Cat> cats = new ArrayList<Cat>(Arrays.asList(new Cat(), new Cat())); | |
// もしListがCovariantであれば可能な代入をJavaで? extendsを使わずに無理やり書く。 | |
List<Animal> animals = (List<Animal>) (List<? extends Animal>) cats; | |
for (Animal animal : animals) { // Cat, Cat, | |
out.print(animal.getClass().getSimpleName() + ", "); | |
} | |
out.println(); | |
animals.add(new Animal()); // ここではエラーにならない。JavaのGenericsは実行時には型情報を失っているため。 | |
for (Animal animal : animals) { // Cat, Cat, Animal, (Animalが追加されていることに注意) | |
out.print(animal.getClass().getSimpleName() + ", "); | |
} | |
out.println(); | |
for (Cat cat : cats) { // ClassCastException (AnimalをCatにキャストできない) | |
out.print(cat.getClass().getSimpleName() + ", "); | |
} | |
out.println(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment