Java Reference
In-Depth Information
Collections and the need for Type Safety
Java'sCollectionsFrameworkmakesitpossibletostoreobjectsinvariouskindsofob-
jectcontainers(knownascollections)andlaterretrievethoseobjects.Forexample,you
canstoreobjectsinalist,aset,oramap.Youcanthenretrieveasingleobject,oriterate
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
compilerdidnotcheckanobject'stypetoseeifitwassuitablebeforeitwasaddedtoa
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)
{
this.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