OnJava8-Examples/generics/CheckedList.java

31 lines
994 B
Java
Raw Normal View History

2015-04-20 15:36:01 -07:00
//: generics/CheckedList.java
2015-05-29 14:18:51 -07:00
// <20>2015 MindView LLC: see Copyright.txt
2015-04-20 15:36:01 -07:00
// Using Collection.checkedList().
import typeinfo.pets.*;
import java.util.*;
public class CheckedList {
@SuppressWarnings("unchecked")
static void oldStyleMethod(List probablyDogs) {
probablyDogs.add(new Cat());
2015-05-18 23:05:20 -07:00
}
2015-04-20 15:36:01 -07:00
public static void main(String[] args) {
2015-05-05 11:20:13 -07:00
List<Dog> dogs1 = new ArrayList<>();
2015-04-20 15:36:01 -07:00
oldStyleMethod(dogs1); // Quietly accepts a Cat
List<Dog> dogs2 = Collections.checkedList(
2015-05-05 11:20:13 -07:00
new ArrayList<>(), Dog.class);
2015-04-20 15:36:01 -07:00
try {
oldStyleMethod(dogs2); // Throws an exception
} catch(Exception e) {
System.out.println("Expected: " + e);
2015-04-20 15:36:01 -07:00
}
// Derived types work fine:
List<Pet> pets = Collections.checkedList(
2015-05-05 11:20:13 -07:00
new ArrayList<>(), Pet.class);
2015-04-20 15:36:01 -07:00
pets.add(new Dog());
pets.add(new Cat());
}
} /* Output:
Expected: java.lang.ClassCastException: Attempt to insert class typeinfo.pets.Cat element into collection with element type class typeinfo.pets.Dog
2015-05-05 11:20:13 -07:00
*///:~