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

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

问题描述

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

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<>();

推荐答案

这两段代码是等效的,并创建具有 type (在您的示例中为myObject)的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<>();

但是,第二个示例使用Java 7中引入的 diamond运算符(<>).它添加了类型推断,并减少了赋值的冗长性.

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

请参见文档:

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

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>>();

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

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天全站免登陆