可变参数方法和原始类型 [英] Varargs methods and primitive types

查看:28
本文介绍了可变参数方法和原始类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Effective Java 中,J. Bloch 提到对原始类型使用可变参数方法是不安全的.准确地说,Arrays.asList(1, 2, 4) 具有返回类型 List ,这听起来很合理.现在我试图自己重现这种行为,但不能:

In Effective Java J. Bloch mentioned that it was not safe to use varargs method with primitive types. Percisely, Arrays.asList(1, 2, 4) had return type List<int[]> and it sounds quite reasonble. Now I tried to reproduce this behaviour myself and couldn't:

我的问题是为什么类型推导出为 List 而不是 List 正如他所说的那样?这是否意味着,在 Java 8 中,关于可变参数的问题不再相关,如果我们不太关心性能,我们可以安全地在任何我们想要的地方使用它们.

My question is why is the type deduced to List<Integer> but not to List<int[]> as he stated? Does it mean, that in Java 8 the problem about varargs is not relevant anymore and we can safely use them anywhere we want if we don't care about performance too much.

推荐答案

作者很可能的意思是你不能传递原始类型元素的数组并期望它像装箱一样

Author most probably meant that you can't pass array of primitive type elements and expect it to be boxed like

int[] intArray = {1,2,3};
Arrays.asList(intArray);

将返回 List 而不是 List 因为没有像 int[]->Integer 这样的数组的自动装箱[] 所以只有 T... 可变参数可以使用的可能类型是 int[] 因为泛型类型 T 可以'不代表原始类型.

which will return List<int[]> not List<Integer> since there is no autoboxing of arrays like int[]->Integer[] so only possible type which can be used by T... vararg is int[] since generic type T can't represent primitive type.

其他可能的问题是您正在阅读本书的第一版(2001 年发布),但自动装箱是在 2004 年发布的 Java 1.5(Java 5.0)中添加的.

Other possible problem is that you are reading first edition of book (released in 2001) but autoboxing was added in Java 1.5 (Java 5.0) which was released in 2004.

这篇关于可变参数方法和原始类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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