Java Generics List and ArrayList with and without Parameters

蓝咒 提交于 2021-01-28 13:10:35

问题


I'm reading about Java Generics. and I want to ask what is the difference between the following statements.

1: List<String> list = new ArrayList(3);

2: List<String> list = new ArrayList<String>(2);

3: List<String> list = new ArrayList<String>();

4a: List<String> list = new ArrayList("A"); // why I can't use String?

4b: List<String> list = new ArrayList('a'); // but char works fine.

I'm reading Java Docs on Generics and after that I need to ask the above questions because I didn't get exact answer.(May be due to poor English)


回答1:


This has nothing to do with generics. ArrayList has a constructor that takes an int, which represents the initial capacity of the List. A char ('a') is convertible to int, which is why 4b works just like 1 and 2. There's no constructor that takes a String, so 4a doesn't pass compilation.

EDIT:

Instantiating a class using a raw type (i.e. without a type parameter, as in List<String> list = new ArrayList(3)), is something you shouldn't do, as it is less type safe, and is only allowed for backwards compatibility.




回答2:


The ArrayList constructor you're using has nothing to do with the generic type. It simply takes an int signifying its initial capacity.

When you call new ArrayList('a'), you're simply promoting 'a' to an int (65).



来源:https://stackoverflow.com/questions/32783401/java-generics-list-and-arraylist-with-and-without-parameters

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