Initializing arraylist without object type - JAVA [duplicate]

杀马特。学长 韩版系。学妹 提交于 2020-01-30 08:34:25

问题


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

回答1:


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



回答2:


In your second example, Java assumes the type is myObject. So there is still a type.



来源:https://stackoverflow.com/questions/47413609/initializing-arraylist-without-object-type-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!