java中参数化和原始类型实例化之间的区别

java中参数化和原始类型实例化之间的区别

本文介绍了java中参数化和原始类型实例化之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说一下,我有一个类 Alpha ,它有两个形式参数 K和V



现在,我想用具体类型 CK和CV 来初始化它的一个对象。



我想知道,

  Alpha< CK,CV> alpha = new Alpha< CK,CV>(); 



  Alpha< CK,CV> alpha = new Alpha(); 

因为这两者都不允许我写或读任何除声明之外的东西。而且,因为泛型只是用于确保编译期间的类型安全,为什么它会在我不能做出任何错误的时候抛出警告?解析方案 / b>

  Alpha< CK,CV> alpha = new Alpha(); 

是在左侧,您使用的是泛型类型Alpha,在右侧正在使用原始类型Alpha。 Java中的原始类型实际上只存在与先前泛型代码的兼容性,除非您绝对必须在新代码中使用它。



至于原始示例 Alpha< CK,CV> alpha = new Alpha(),编译器会为该分配生成警告,因为它必须。考虑一下:

  List< String> strings = ... //包含某些字符串的某些列表

//完全合法,因为您使用了原始类型并丢失了所有类型的检查!
列表<整数>整数=新的LinkedList(字符串);

泛型提供编译时保护,防止错误操作。在上面的例子中,使用原始类型意味着你没有得到这种保护,并会在运行时得到一个错误。这就是为什么你不应该使用原始类型。

  //不合法,因为右侧实际上是通用的! 
列表<整数>整数=新的LinkedList<>(字符串);


Say, I have a class Alpha with two formal parameters K and V.

Now, I want to initialize an object of it with concrete types CK and CV.

I want to know, what's the difference between

Alpha<CK, CV> alpha = new Alpha<CK, CV>();

and,

Alpha<CK, CV> alpha = new Alpha();

Since, both won't allow me to write or read anything other than what they are declared as. And, since, generics is only for ensuring type safety during compile time, why does it throws warning if I can't do anything wrong with it?

解决方案

The issue with

Alpha<CK, CV> alpha = new Alpha();

is that on the left hand side, you are using the generic type Alpha where on the right side you are using the raw type Alpha. Raw types in Java effectively only exist for compatibility with pre-generics code and should never be used in new code unless you absolutely have to.

As far as your original example of Alpha<CK, CV> alpha = new Alpha(), the compiler generates a warning for that assignment because it must. Consider this:

List<String> strings = ... // some list that contains some strings

// Totally legal since you used the raw type and lost all type checking!
List<Integer> integers = new LinkedList(strings);

Generics exist to provide compile-time protection against doing the wrong thing. In the above example, using the raw type means you don't get this protection and will get an error at runtime. This is why you should not use raw types.

// Not legal since the right side is actually generic!
List<Integer> integers = new LinkedList<>(strings);

这篇关于java中参数化和原始类型实例化之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 05:48