public class MyType<E> {class Inner { }static class Nested { }
public static void main(String[] args) {MyType mt; // warning: MyType is a raw typeMyType.Inner inn; // warning: MyType.Inner is a raw type
MyType.Nested nest; // no warning: not parameterized typeMyType<Object> mt1; // no warning: type parameter givenMyType<?> mt2; // no warning: type parameter given (wildcard OK!)}}
List names = new ArrayList(); // warning: raw type!names.add("John");names.add("Mary");names.add(Boolean.FALSE); // not a compilation error!
上面的代码运行得很好,但假设您还有以下内容:
for (Object o : names) {String name = (String) o;System.out.println(name);} // throws ClassCastException!// java.lang.Boolean cannot be cast to java.lang.String
static void appendNewObject(List<?> list) {list.add(new Object()); // compilation error!}//...
List<String> names = new ArrayList<String>();appendNewObject(names); // this part is fine!
List aList = new ArrayList();String s = "Hello World!";aList.add(s);String c = (String)aList.get(0);
虽然这工作的大部分时间错误确实发生
List aNumberList = new ArrayList();String one = "1";//Number oneaNumberList.add(one);Integer iOne = (Integer)aNumberList.get(0);//Insert ClassCastException here
List<String> aNumberList = new ArrayList<String>();aNumberList.add("one");Integer iOne = aNumberList.get(0);//Compile time errorString sOne = aNumberList.get(0);//works fine
比较:
// Old style collections now known as raw typesList aList = new ArrayList(); //Could contain anything// New style collections with GenericsList<String> aList = new ArrayList<String>(); //Contains only Strings
更复杂的Compareable接口:
//raw, not type save can compare with Other classesclass MyCompareAble implements CompareAble{int id;public int compareTo(Object other){return this.id - ((MyCompareAble)other).id;}}//Genericclass MyCompareAble implements CompareAble<MyCompareAble>{int id;public int compareTo(MyCompareAble other){return this.id - other.id;}}
arr.add("hello");// alone statement will compile successfully and no warning.
arr.add(23); //prone to compile time error.//error: no suitable method found for add(int)
arr.add("hello"); //alone this compile but raise the warning.arr.add(23); //again prone to compile time error.//error: no suitable method found for add(int)
//Use of raw type : don't !private final Collection stamps = ...stamps.add(new Coin(...)); //Erroneous insertion. Does not throw any errorStamp s = (Stamp) stamps.get(i); // Throws ClassCastException when getting the Coin
//Common usage of instance ofif (o instanceof Set){Set<?> = (Set<?>) o;}