向Arraylist添加值 [英] Adding values to Arraylist

查看:1116
本文介绍了向Arraylist添加值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码1:

ArrayList arr = new ArrayList();
arr.add(3);
arr.add("ss");

代码2:

ArrayList<Object> arr = new ArrayList<Object>();
arr.add(3);
arr.add("ss");

代码3:

ArrayList<Object> arr = new ArrayList<Object>();
arr.add(new Integer(3));
arr.add(new String("ss"));

上述所有三个代码都工作正常..有人可以告诉我哪个是优先的,为什么..以及为什么eclipse编译器总是在没有提到Arraylist的参数类型时发出警告..提前感谢..

all the above three codes are working fine.. can some one tell me the which is prefered and why.. and why the eclipse compiler always gives warning when type of arguments are not mentioned to the Arraylist.. thanks in advance..

推荐答案

第一个简单的规则:永远不要使用 String(String)构造函数,它绝对没用(*)

First simple rule: never use the String(String) constructor, it is absolutely useless (*).

所以 arr.add(ss)就好了。

随着 3 略有不同: 3 是一个 int 字面值,这不是一个对象。只能将对象放入列表。因此需要将 int 转换为 Integer 对象。在大多数情况下,将为您自动完成(该过程称为自动装箱)。它有效地 Integer.valueOf(3)做同样的事情可以(并且将)避免创建新的在某些情况下,整数实例。

With 3 it's slightly different: 3 is an int literal, which is not an object. Only objects can be put into a List. So the int will need to be converted into an Integer object. In most cases that will be done automagically for you (that process is called autoboxing). It effectively does the same thing as Integer.valueOf(3) which can (and will) avoid creating a new Integer instance in some cases.

所以实际上写 arr.add(3) 通常比使用 arr.add(new Integer(3))更好的主意,因为可以避免创建新的整数对象,而是重复使用现有对象。

So actually writing arr.add(3) is usually a better idea than using arr.add(new Integer(3)), because it can avoid creating a new Integer object and instead reuse and existing one.

免责声明:我关注的是第二个和第三个代码块之间的区别,而且几乎忽略了泛型部分。有关泛型的更多信息,请查看其他答案。

Disclaimer: I am focusing on the difference between the second and third code blocks here and pretty much ignoring the generics part. For more information on the generics, please check out the other answers.

(*)有一些模糊的角落情况有用,但是一旦你接近那些,你就会知道永远不要把绝对的陈述当作绝对的; - )

(*) there are some obscure corner cases where it is useful, but once you approach those you'll know never to take absolute statements as absolutes ;-)

这篇关于向Arraylist添加值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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