列表中的差异<整数> l = new ArrayList()和List< Integer> l = new ArrayList< integer>() [英] Difference in List<Integer> l = new ArrayList() and List<Integer> l = new ArrayList<integer>()

查看:191
本文介绍了列表中的差异<整数> l = new ArrayList()和List< Integer> l = new ArrayList< integer>()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下两个声明有什么区别

  List< Integer> l = new ArrayList(); //和

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

如果不是,为什么在java 7 dimond <= c $ c><> ,以避免在'='或者在对象创建端。

解决方案

考虑这个例子

 列表与LT;浮法> f = new ArrayList(); //这个列表保存(s)Float(s)。 
f.add(2.0f);
列表<整数> l = new ArrayList(f); //哦,不....
l.add(1);
System.out.println(l);

如果我运行上述,我会得到



<$如果我使用了菱形运算符,那么我们可以使用菱形运算符,我会得到一个编译器错误。这有帮助吗?
在运行时,每个Collection由于类型擦除而持有java.lang.Ojbect(s),这只是编译时类型检查。


What is difference in following two declarations

List<Integer> l = new ArrayList(); //and 

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

If not then why in java 7 dimond operator ie <> is introduced to avoid type writing at right side of '=' or at object creation side.

解决方案

Consider this example

List<Float> f = new ArrayList();     // this list hold(s) Float(s).
f.add(2.0f);
List<Integer> l = new ArrayList(f);  // Oh no.... 
l.add(1);
System.out.println(l);            

If I run the above I get

[2.0, 1]

If I used the diamond operator, I would get a compiler error. Does that help? At run-time every Collection holds java.lang.Ojbect(s) due to type erasure, this is compile time type checking only.

这篇关于列表中的差异&lt;整数&gt; l = new ArrayList()和List&lt; Integer&gt; l = new ArrayList&lt; integer&gt;()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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