我正在阅读有关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
发布评论