问题
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