Java泛型:在ArrayList(无界通配符类型)上,add和addAll方法的行为有所不同 [英] Java Generics: On arraylist (unbounded wildcard type), add and addAll methods behaves differently

查看:569
本文介绍了Java泛型:在ArrayList(无界通配符类型)上,add和addAll方法的行为有所不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  ArrayList<?> x = new ArrayList(); 
ArrayList y = new ArrayList();
x.add(abc); //第1条。编译错误 - 没问题。了解。
x.addAll(y); //没有编译错误

对于无界通配符,不能添加。为什么上一条语句没有编译错误?

解决方案

因为您正在使用原始类型调用该方法。编译器不能执行类型检查。如果您制作 y 用户泛型, addAll(..)将会失败。


To be direct here's an example:

    ArrayList <?> x = new ArrayList();
    ArrayList y = new ArrayList();
    x.add("abc"); // Clause 1. Compilation error - No problemo. Understood.
    x.addAll(y); // Clause 2. No compilation error

For unbounded wildcard, one cannot add. Why there is no compilation error on the last statement?

解决方案

Because you are invoking the method with a raw type. The compiler can't perform type checks. If you make y user generics, addAll(..) will fail.

这篇关于Java泛型:在ArrayList(无界通配符类型)上,add和addAll方法的行为有所不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆