Java泛型列表和带有和不带有参数的ArrayList [英] Java Generics List and ArrayList with and without Parameters
问题描述
我正在阅读有关Java泛型的内容.我想问一下以下语句之间有什么区别.
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");
//为什么我不能使用String?
4a: List<String> list = new ArrayList("A");
// why I can't use String?
4b: List< String>list = new ArrayList('a');
//但是char可以正常工作.
4b: List<String> list = new ArrayList('a');
// but char works fine.
我正在阅读有关泛型的Java文档我需要问上述问题,因为我没有得到确切的答案.(可能是由于英语不佳)
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)
推荐答案
这与泛型无关. ArrayList
具有一个采用 int
的构造函数,该构造函数表示List的初始容量.一个 char
('a'
)可以转换为 int
,这就是为什么4b的工作方式与1和2相同的原因. String
,因此4a不会通过编译.
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.
使用原始类型(即,没有类型参数,例如,在 List< String> list = new ArrayList(3)
中)实例化类是您不应该做的事情,因为它是类型安全性较低,并且仅允许向后兼容.
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.
这篇关于Java泛型列表和带有和不带有参数的ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!