Raw types refer to using a generic type without specifying a type parameter. For example, List is a raw type, while List is a parameterized type.
When generics were introduced in JDK 1.5, raw types were retained only to maintain backwards compatibility with older versions of Java. Although using raw types is still possible, they should be avoided :
- they usually require casts
- they aren't type safe, and some important kinds of errors will only appear at runtime
- they are less expressive, and don't self-document in the same way as parameterized types
Example
import java.util.*;
public final class AvoidRawTypes {
void withRawType(){
//Raw List doesn't self-document,
//doesn't state explicitly what it can contain
List stars = Arrays.asList("Arcturus", "Vega", "Altair");
Iterator iter = stars.iterator();
while(iter.hasNext()) {
String star = (String) iter.next(); //cast needed
log(star);
}
}
void withParameterizedType(){
Liststars = Arrays.asList("Spica", "Regulus", "Antares");
for(String star : stars){
log(star);
}
}
private void log(Object aMessage) {
System.out.println(String.valueOf(aMessage));
}
}
Comments
Post a Comment