花式泛型捕获碰撞 [英] Fancy generics capture collision

查看:95
本文介绍了花式泛型捕获碰撞的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



 列表<?>请给我一个提示,告诉我们这里发生了什么:

扩展Number> a = new ArrayList< Number>();
列表< ;?扩展Number> b = new ArrayList< Number>();

a.addAll(b); //哎!编译器对我大喊,看下面的块:
/ *
不兼容类型
found:java.util.List< capture#714 of?扩展java.lang.Number>
required:java.util.List< java.lang.Number>
* /

这个简单的代码不能编译。我隐约记得与类型捕获有关的东西,比如那些应该主要用在接口规范中,而不是实际的代码,但我从来没有像这样傻眼。



这当然可能会像这样蛮力地修复:

  List< ;?扩展Number> a = new ArrayList< Number>(); 
列表< ;?扩展Number> b = new ArrayList< Number>();

@SuppressWarnings({unchecked})
List< Number> aPlain =(List< Number>)a;
@SuppressWarnings({unchecked})
List< Number> bPlain =(List< Number>)b;

aPlain.addAll(bPlain);

因此,我真的必须放弃声明中的捕获(捕获来自我的界面,所以我不得不改变一些API),或者坚持使用抑制注释的类型转换(它通常会使代码变得复杂并且复杂一些)?

? extends Number 表示扩展 Number 的类。因此,对于 a 列表,它可以是 classA 和列表 b 它可以是例如 classB 。它们不兼容,它们可以完全不同。


Please give me a hint as to what is going on here:

List<? extends Number> a = new ArrayList<Number>();
List<? extends Number> b = new ArrayList<Number>();

a.addAll(b); // ouch! compiler yells at me, see the block below:
/*
  incompatible types
  found   : java.util.List<capture#714 of ? extends java.lang.Number>
  required: java.util.List<java.lang.Number>
 */

This simple code does not compile. I vaguely remember something related to type captures, like those should be mostly used in interface specs, not the actual code, but I never got dumbfounded like that.

This of course might be fixed brute-forcefully, like that:

List<? extends Number> a = new ArrayList<Number>();
List<? extends Number> b = new ArrayList<Number>();

@SuppressWarnings({"unchecked"})
List<Number> aPlain = (List<Number>) a;
@SuppressWarnings({"unchecked"}) 
List<Number> bPlain = (List<Number>) b;

aPlain.addAll(bPlain); 

So, do I really have to either give up captures in the declaration (the capture came to me from an interface, so I'll have to change some API), or stick with type casts with suppression annotations (which generally suck and complicates code a bit)?

解决方案

You have essentially two lists of possibly different types. Because ? extends Number means a class which extends Number. So for list a it can be classA and for list b it can be for example classB. They are not compatible, they can be totally different.

这篇关于花式泛型捕获碰撞的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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