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<String> 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<E> 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<E>
  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<E>
  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
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值