开发者

java generics problem when converting from array to vector

Why is this not allowed? arr is a double[].

Vector<Double> v = new Vector<Double&开发者_如何转开发gt;(Arrays.asList(arr));

I get a unrecognized constructor error. It thinks i'm trying to use the Vector(java.util.List<double[]>) constructor which seems odd cuz why would it be a list of double[]s? It compiles if i make it this

Vector<Double> v = new Vector(Arrays.asList(arr));

but then I get a warning about unchecked assignment


It's because Double is not the same as double in Java.

Arrays.asList doesn't work with primitives, so when you're calling it with a double[] as its first parameter, it thinks you're passing in the array itself as the first argument in the ...-style argument list. Therefore, Arrays.asList returns a List of double[], containing only a single element: the double[] that you passed in.


Generics like List<double> do not permit primitive types and this is why your program is failing.

You need to iterate the array and fill up your collection item by item. Or you can use the ArrayUtils.toObject() method to convert from double[] to Double[]. That class is found int the Apache Commons library.


Just to clarify, 'double' is a primitive type, like 'int' or 'char'. 'Double' is a class type. You can make a vector of . Change the original array to be an array of 'Double's, not 'double's.


Arrays.asList(T... a) doesn't work as expected with primitive arrays, because generics and primitives don't get along very well. The compiler is using double[] for T, which is why Arrays.asList is returning a List<double[]>.

I think the shortest code to get what you want is:

Vector<Double> v = new Vector<Double>(arr.length);
for (double d : arr) v.add(d);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜