Java Reference
In-Depth Information
Java 5 generic types
One of the most notable additions to Java 5 is “generic types,” such as collections, that are
defined to hold objects of a certain type rather than just Object (obviating the downcast oth-
erwise needed each time you get an object back from a collection). For example, with a List
of String s, prior to 1.5 you might have written the code in Example A-3 .
Example A-3. ListsOldAndNew.java
List myList = new
new ArrayList ();
myList . add ( "hello" );
myList . add ( "goodbye" );
// myList.add(new Date()); This would compile but cause failures later
for
for ( int
int i = 0 ; i < myList . size (); i ++) {
String s = ( String ) myList . get ( i );
System . out . println ( s );
}
In Java 5, you would be more likely to write this as:
List < String > myList = new
new ArrayList <>(); // Java 6: new ArrayList<String>();
myList . add ( "hello" );
myList . add ( "goodbye" );
// myList.add(new Date()); This would not compile!
for
for ( String s : myList ) { // Look Ma, no downcast!
System . out . println ( s );
}
This mechanism is called “generics” because it allows you to write generic classes, the argu-
ments and return types of methods of which are specified when the class is instantiated.
Although the original definition of the List interface and the ArrayList class had methods
dealing in java.lang.Object , in 1.5 these types have been changed to a Generic type or
“type parameter” so that you can declare and instantiate them with any object type ( String ,
Customer , Integer ), and get the benefits of stronger type checking and elimination of
downcasts.
Search WWH ::




Custom Search