Varargs methods and primitive types [duplicate]

不羁的心 提交于 2020-02-06 06:05:56

问题


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:

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.


回答1:


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);

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.


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.



来源:https://stackoverflow.com/questions/37098205/varargs-methods-and-primitive-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!