为何放弃泛型运算符时无法推断出类型 [英] Why type is not inferred when leaving away generics operator

查看:48
本文介绍了为何放弃泛型运算符时无法推断出类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读到,从Java 7开始,像在第一条语句中那样在右侧指定类型创建Collections是不好的样式,因为编译器可以从左侧推断类型.

I read that since Java 7, creating Collections with specifying the type on the right side like in the first statement is bad style because the compiler can infer the type from the left side.

List<Integer> myList = new ArrayList<Integer>();

我的问题是,当像这样初始化列表时,编译器找不到类型,并且我收到未经检查的类型警告:

My question is when initializing the list like this, the compiler does not find the type and I get an unchecked type warning:

List<Integer> myList = new ArrayList(); 

推荐答案

编译器不会推断类型,因为您正在实例化 raw ArrayList .但是它足够聪明,可以警告您在使用此(原始)对象时可能会出现问题.

The compiler doesn't infer the type, because you're instantiating a raw ArrayList. But it's smart enough to warn you that there might be problems when working with this (raw) object.

值得一提的是此警告背后的原因.由于类型擦除,参数信息(当变量包含 Object 类型的元素时,有关 List 的< Integer> )将在运行时完全消失.请考虑以下代码段:

It's worth mentioning the reason behind this warning. Due to the type erasure, the parametric information (<Integer>) about the List will be completely gone at Runtime, when the variable would hold elements of type Object. Consider this snippet:

List rawList = new ArrayList(); //raw list
rawList.add(new String("hello"));
rawList.add(new Double(12.3d));
List<Integer> intList = rawList; // warning!

此代码段将编译,但不会生成警告.具有原始列表( rawList ),您可以将任何非基本类型添加到列表中,包括 String Double 等.但是当将此集合分配给一个列表,该列表被指定为仅容纳 整数,那么这是一个问题.在运行时,当尝试从 intList 中获取某些元素时,会得到一个 ClassCastException ,该元素应该是一个 Integer ,但实际上是 String 或其他名称.

This snippet will compile, but will generate few warnings. Having a raw list (rawList), you can add any non-primitive type to the list, including String, Double, etc. But when assigning this collection to a list, which is specified to hold only integers, then this is a problem. At Runtime you'll get a ClassCastException when trying to fetch some element from the intList, which is supposed to be an Integer, but in reality is a String or something else.

长话短说-请勿将原始类型与泛型混用!

Long story short - do not mix raw types with Generics!

在您的情况下,如果您使用菱形,则编译器可能已经推断出类型:

In your case, the compiler would possibly have inferred the type, if you have used the diamond:

List<Integer> list = new ArrayList<>(); //¯\_(ツ)_/¯
                                  ↑↑

这篇关于为何放弃泛型运算符时无法推断出类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆