java Generic Type/Parameterized Type/Raw Type

转载地址:http://www.herongyang.com/Java/Generic-Class-Raw-Generic-Parameterized-Type.html

What Is a Generic Type? A generic type is a generic class or interface that uses type parameters.

What Is a Parameterized Type? A parameterized type is a parameterized version of a generic class or interface. For example, Vector is a parameterized type.

What Is a Raw Type? A raw type is a parameterized type with the parameter type argument omitted. For example, Vector is raw type.

Raw types are supported in Java to keep legacy applications working. In most cases, a raw type is equivalent a parameterized type with "Object" as the type argument.

Here is a legacy example that still uses a raw type of the Vector generic class.

/* RawTypeTest.java
 - Copyright (c) 2014, HerongYang.com, All Rights Reserved.
 */
import java.util.*;
class RawTypeTest {
   public static void main(String[] a) {
      java.io.PrintStream o = System.out;

      Vector myList = new Vector();
      myList.add(new String("Milk"));
      myList.add(new Float(3.99));

      String name = (String) myList.get(0);
      Float price = (Float) myList.get(1);
      o.println(name+": "+price);
   }
}

Compile and run this example. You will get:

C:\herong>javac RawTypeTest.java

Note: RawTypeTest.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

C:\herong>java RawTypeTest
Milk: 3.99

As you can see, the compiler let you to use raw types. But it gives you the "unchecked or unsafe operations" warning. If you recompile it with the "-Xlint", you will see more details:

C:\herong>javac -Xlint RawTypeTest.java

RawTypeTest.java:9: warning: [rawtypes] found raw type: Vector
      Vector myList = new Vector();
      ^
  missing type arguments for generic class Vector
  where E is a type-variable:
    E extends Object declared in class Vector
RawTypeTest.java:9: warning: [rawtypes] found raw type: Vector
      Vector myList = new Vector();
                          ^
  missing type arguments for generic class Vector
  where E is a type-variable:
    E extends Object declared in class Vector
RawTypeTest.java:10: warning: [unchecked] unchecked call to add(E) as
a member of the raw type Vector
      myList.add(new String("Milk"));
                ^
  where E is a type-variable:
    E extends Object declared in class Vector
RawTypeTest.java:11: warning: [unchecked] unchecked call to add(E) as
a member of the raw type Vector
      myList.add(new Float(3.99));
                ^
  where E is a type-variable:
    E extends Object declared in class Vector
4 warnings

你可能感兴趣的:(java)