2014-09-19 70 views
-4

类别MyClass的对象与类MyClass<String>的对象除了一个是'Raw Type'而另一个是'Generic type'这个事实之外是否有任何区别。如果我们在Raw对象上调用'getClass()'方法键入'MyClass'和通用类型MyClass<String>的对象都将返回相同的答案。那么究竟有什么不同呢?谢谢普通类的对象与泛型类的对象是否有区别?

class MyClass 
{ 

} 


class MyClass<String> 
{ 

} 
+0

阅读请:http://stackoverflow.com/help/how-请求 – folkol 2014-09-19 05:52:33

+6

第一个是* raw *,另一个是通用的 – 2014-09-19 05:52:34

+1

您不能使用相同的完全限定名称定义这两个类。 – Boann 2014-09-19 05:52:49

回答

0

泛型提供编译时类型安全性,并确保您只在集合中插入正确的类型并避免运行时发生ClassCastException。

现在,例如向您展示简单的优势,我已经提供了这个代码

public class Box<T> { 

    private T t; 

    public void add(T t) { 
    this.t = t; 
    } 

    public T get() { 
    return t; 
    } 

    public static void main(String[] args) { 
    Box<Integer> integerBox = new Box<Integer>(); 
    Box<String> stringBox = new Box<String>(); 

    integerBox.add(new Integer(10)); 
    stringBox.add(new String("Hello World")); 

    System.out.printf("Integer Value :%d\n\n", integerBox.get());//10 
    System.out.printf("String Value :%s\n", stringBox.get());//Hello World 
    } 
} 

更多细节,您可以检查this link

相关问题