## 突然发现这标题里面的<>貌似被限制了???
一,集合添加元素
1, 普通集合List
public static void main(String[] args) {
List<String> strings = new ArrayList<>();
unsafeAdd(strings, new Integer(42));
System.out.println(strings.get(0));
}
public static void unsafeAdd(List list, Object obj) {
list.add(obj);
}
以上代码编译时会出现警告提示:
Type safety: The method add(Object) belongs to the raw type List. References to generic type List<E> should be parameterized
表示代码存在安全风险, 这时候就需要慎重处理, 尽量消除警告或者在确保不会出问题的情况下进行选择性忽略。
运行以上代码, 向集合里添加元素, 会出现报错:
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
类型转换的时候出现异常,这种情况就体现了泛型存在的必要性,对传参类型进行统一约束。
2,泛型List<Object>
public static void main(String[] args) {
List<String> strings = new ArrayList<>();
unsafeAdd(strings, new Integer(42));
System.out.println(strings.get(0));
}
public static void unsafeAdd(List<Object> list, Object obj) {
list.add(obj);
}
改造之后的代码对传参进行了类型约束,对于类型问题在编译时就会报错:
The method unsafeAdd2(List<Object>, Object) in the type FanXing01 is not applicable for the arguments (List<String>, Integer)
从而避免了等到代码运行时才发现类型转换有问题的情况。
二, 无限制的通配符类型List<?>
1,能用get()访问元素, 不能用add()添加元素
public static void main(String[] args) {
List<String> strings = new ArrayList<>();
unsafeAdd(strings, new Integer(42));
System.out.println(strings.get(0));
}
public static void unsafeAdd(List<?> list, Object obj) {
list.add(obj);
}
以上代码编译时就会报错:
扫描二维码关注公众号,回复:
4533007 查看本文章
The method add(capture#1-of ?) in the type List<capture#1-of ?> is not applicable for the arguments (Object)
由于List<?>不确定即将传进来的参数是具体是什么类型, 如果将Object类型的值add进去就可能会出现类型转换异常, 所以编译不通过。
2,E<?>应用实例
具体实现过程见对应源码