初始化没有对象类型的arraylist - JAVA [英] Initializing arraylist without object type - JAVA

查看:25
本文介绍了初始化没有对象类型的arraylist - JAVA的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题不是关于为什么我们将列表初始化为接口而不是实现,例如

Listobj = new ArrayList();

问题是以下两者之间有什么区别,为什么它们(显然)以相同的方式工作?

//list 和 arraylist 都有一个类型列表obj = new ArrayList();//arraylist没有类型列表obj = 新的 ArrayList();

解决方案

两段代码是等价的,并且创建了 ArrayListtype (myObject 在您的示例中):

Listobj = new ArrayList();

Listobj = 新的 ArrayList();

然而,第二个示例使用了 Java 7 中引入的 菱形运算符(<>).它增加了类型推断并减少了赋值的冗长.<小时>

请参阅 文档:

<块引用>

您可以替换调用构造函数所需的类型参数具有空类型参数集 (<>) 的泛型类因为编译器可以从上下文推断类型参数.这个一对尖括号非正式地称为菱形.

例如,考虑以下变量声明:

Map>myMap = new HashMap>();

在 Java SE 7 中,您可以替换参数化类型带有空类型参数集的构造函数 (<>):

Map>myMap = new HashMap<>();

This question is not about why we initialize a list as interface over implementation e.g.

List<myObject> obj = new ArrayList<myObject>();

The question is what is the difference between the following two and why do they (apparently) work the same way?

//list and arraylist both have a type
List<myObject> obj = new ArrayList<myObject>();

//arraylist does not have a type
List<myObject> obj = new ArrayList<>();

解决方案

Both pieces of code are equivalent and create ArrayLists with a type (myObject in your example):

List<myObject> obj = new ArrayList<myObject>();

List<myObject> obj = new ArrayList<>();

However the second example uses the diamond operator (<>) introduced in Java 7. It adds type inference and reduces the verbosity in the assignments.


See the following quote from the documentation:

You can replace the type arguments required to invoke the constructor of a generic class with an empty set of type parameters (<>) as long as the compiler can infer the type arguments from the context. This pair of angle brackets is informally called the diamond.

For example, consider the following variable declaration:

Map<String, List<String>> myMap = new HashMap<String, List<String>>();

In Java SE 7, you can substitute the parameterized type of the constructor with an empty set of type parameters (<>):

Map<String, List<String>> myMap = new HashMap<>();

这篇关于初始化没有对象类型的arraylist - JAVA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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