Java泛型集合疑问
我在使用泛型时遇到了麻烦。我定义了以下静态方法:
public static <E extends Number> List<E> group(E ... numbers) {
return Arrays.asList(numbers);
}
我明白为什么它有效:
List<Integer> ints = group(1, 2, 3);
但是我必须在方法签名中更改什么才能使其工作:
List<Number> ints = group(1, 2, 3);
或者我应该调用将 Number 类型指定为的组方法:
List<Number> ints = MyClass.<Number>group(1, 2, 3);
提前致谢。
I'm having trouble with a generics. I have defined the following static method:
public static <E extends Number> List<E> group(E ... numbers) {
return Arrays.asList(numbers);
}
I understand why this works:
List<Integer> ints = group(1, 2, 3);
But what do I have to change in my method signature to make this work:
List<Number> ints = group(1, 2, 3);
Or should I just call the group method specifying the Number type as:
List<Number> ints = MyClass.<Number>group(1, 2, 3);
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要按照您的建议显式指定
Number
作为类型参数。You need to explicitly specify
Number
as the type argument, as you suggested.您将无法获取
List
。如果您的方法
group(1,2,3)
返回一个List
,并且您说它有效,那么此表达式的类型为List;
。并且
List
不是List
。继承意味着专业化,因此如果您的List
是一种List
,您可以将Double
添加到您的>List
(超类可以做到,子类也可以做到)。这是错误的。这不是转换问题,它只会将编译问题推迟到运行时。这个问题是合乎逻辑的,对人类来说是一个相当矛盾的问题,但这就是集合和继承的工作方式。
因此,如果您确实想获得
List
我建议您定义第二种方法:问候,
史蒂芬
You won't be able to do get a
List<Number>
.If your method
group(1,2,3)
return aList<Integer>
, and you said that worked, so this expression is of typeList<Integer>
.And
List<Integer>
is not aList<Number>
. Inheritance means specialization, so if yourList<Integer>
would be a kind ofList<Number>
you could addDouble
s to yourList<Integer>
(as the super class can do it, subclass can do it too). And this is wrong.This not a casting problem, it would just postpone your compile problem to runtime. The problem is logical and quite a paradox for humans, but that's the way collection and inheritance work.
So, if you really want to get a
List<Number>
I suggest you define a second method :Regards,
Stéphane