Java泛型列表和带有和不带有参数的ArrayList

编程入门 行业动态 更新时间:2024-10-09 19:15:26
本文介绍了Java泛型列表和带有和不带有参数的ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在阅读有关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

本文发布于:2023-10-30 07:33:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1542194.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:参数   列表   Java   ArrayList

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!