加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – ArrayList是否允许添加String?

发布时间:2020-12-15 03:07:57 所属栏目:Java 来源:网络整理
导读:我遇到了以下代码,一个向List添加元素的简单示例 List list = new ArrayListInteger(); ListIteratorInteger litr = null; list.add("A"); list.add("1"); list.add(5); litr = list.listIterator(); while(litr.hasNext()){ System.out.println("UIterating
我遇到了以下代码,一个向List添加元素的简单示例
List list = new ArrayList<Integer>();
    ListIterator<Integer> litr = null;
    list.add("A");

    list.add("1");

    list.add(5);

    litr = list.listIterator();
    while(litr.hasNext()){
        System.out.println("UIterating " + litr.next());
    }

我希望它抛出一个ClassCastException,而是将它写入控制台

A
1
5

这看起来很奇怪.我试过的时候:

List<Integer> list = new ArrayList<Integer>();

我有一个编译时错误.

如果有人能解释如何将String对象添加到ArrayList,我将不胜感激

解决方法

您已将新ArrayList分配给无类型列表.通用类型限制不适用于无类型列表,它可以让您在其中放置任何内容.编译器不会跟踪您的无类型List是指使用泛型类型声明的内容.

在任何情况下,这都不会产生ClassCastException,泛型只会影响编译.在运行时

将类型放在list变量上的情况:

List<Integer> list = new ArrayList<Integer>();

它是首选,它应该生成一个编译器错误,告诉你在集合中输入了错误的类型.

在this article中描述了遗留,非通用代码和通用代码如何互操作:

In proper generic code,Collection would always be accompanied by a type parameter. When a generic type like Collection is used without a type parameter,it’s called a raw type.

Most people’s first instinct is that Collection really means Collection<Object>. However,as we saw earlier,it isn’t safe to pass a Collection<Part> in a place where a Collection<Object> is required. It’s more accurate to say that the type Collection denotes a collection of some unknown type,just like Collection<?>.

But wait,that can’t be right either! Consider the call to getParts(),which returns a Collection. This is then assigned to k,which is a Collection<Part>. If the result of the call is a Collection<?>,the assignment would be an error.

In reality,the assignment is legal,but it generates an unchecked warning. The warning is needed,because the fact is that the compiler can’t guarantee its correctness. We have no way of checking the legacy code in getAssembly() to ensure that indeed the collection being returned is a collection of Parts. The type used in the code is Collection,and one could legally insert all kinds of objects into such a collection.

So,shouldn’t this be an error? Theoretically speaking,yes; but practically speaking,if generic code is going to call legacy code,this has to be allowed. It’s up to you,the programmer,to satisfy yourself that in this case,the assignment is safe because the contract of getAssembly() says it returns a collection of Parts,even though the type signature doesn’t show this.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读