开发者

Transform array to list

I have the following fragment of code:

public void doSomethi开发者_Python百科ng() {
  float array[] = new float[2];
  array[0] = (float) 0.0;
  array[1] = (float) 1.2;
  someMethod(array);
}

public void someMethod(Object value) {
   //need to convert value to List<Float>
}

As you can see above I want to convert the value variable which is an array (but passed as an Object) to List. I tried the following as suggested here: Create ArrayList from array

    new ArrayList<Float> (Arrays.asList(value));

however, it does not compile.

Any hints?


public void someMethod(Object value) {
    float[] array = (float[]) value;
    List<Float> result = new ArrayList<Float>(array.length);
    for (float f : array) {
        result.add(Float.valueOf(f));
    }
    // ...
}

I don't know why you're not defining the value argument as a float[] rather than an Object, though.


[Updated per JB Nizet's correction.] If you use Float instead of float for the array, it will work if the compiler knows that value is an array - which it doesn't. Add a cast:

new ArrayList<Float> (Arrays.asList((Float[])value));

or just change the parameter type of value to Float[], and leave out the cast.


If you want to view a float[] as a List<Float> then Guava's Floats.asList method will get the job done.


Change float to Float since Arrays.asList(T...a) cannot return a List<float> because a Java primitive type cannot be passed as an argument to a generic type.

public void doSomething() {
    Float array[] = new Float[2];
    array[0] = 0.0f;
    array[1] = 1.2f;
    someMethod(array);
}

public void someMethod(Object value) {
    List<Float> list = new ArrayList<Float> (Arrays.asList((Float[])value));
    System.out.println(list);
}

prints

[0.0, 1.2]
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜