List和List之间的Java差异< Object> [英] Java difference between List and List<Object>

查看:306
本文介绍了List和List之间的Java差异< Object>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在java中 List List< Object> 有什么区别?

$ b $ ; mainList = new ArrayList< Object>();



和一个原始类型:

列表rawList = new ArrayList();



现在让我们做这样的事情:

 列表<整数> intList = new ArrayList< Integer>(); 
intList.add(42);
mainList.addAll(intList);
rawList.addAll(intList);

但是还有一个包含String对象的列表:



列表< String> strList = new ArrayList< String>()



当我们尝试调用时, p> strList.addAll(mainList)



我们得到一个编译错误:

类型List< String>的方法addAll(Collection<?extends String>)不适用于参数(List< Object>)



但是,如果我们试图调用
$ b $ strList.addAll(rawList) code>



我们只收到警告。

所以如果你在应用程序中只使用对象列表,那么List和List之间确实没有区别。但是从Java 1.5开始,使用泛型为应用程序提供编译时类型安全性是个好主意。


What is the difference between List and List<Object> in java?

解决方案

Suppose you've got two lists:

List<Object> mainList = new ArrayList<Object>();

and one with a raw type:

List rawList = new ArrayList();

Now let's do something like this:

List<Integer> intList = new ArrayList<Integer>();
intList.add(42);
mainList.addAll(intList);
rawList.addAll(intList);

But there is somewhere one more list which contains String objects:

List<String> strList = new ArrayList<String>().

When we try to call

strList.addAll(mainList)

we get a Compilation Error :

The method addAll(Collection<? extends String>) in the type List<String> is not applicable for the arguments (List<Object>).

But if we try to call

strList.addAll(rawList)

we get just a warning.

So if you are using only lists of objects in your application it's really no difference between List and List. But since Java 1.5 it's a good idea to use generics for providing compile-time type safety for your application.

这篇关于List和List之间的Java差异&lt; Object&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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