Java Reference
In-Depth Information
Collections and the need for Type Safety
over the collection and retrieve all objects.
Before Java5overhauled theCollections Framework totake advantage ofgenerics,
there was no way to prevent a collection from containing objects of mixed types. The
collection, and this lack of static type checking led to ClassCastException s.
Listing 3-50 demonstrates how easy it is to generate a ClassCastException .
Listing 3-50. Lack of type safety leading to a ClassCastException at runtime
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
class Employee
private String name;
Employee(String name)
{ = name;
String getName()
return name;
class TypeSafety
public static void main(String[] args)
List employees = new ArrayList();
employees.add(new Employee("John Doe"));
employees.add(new Employee("Jane Smith"));
Search WWH ::

Custom Search