I have the following fragment of code:
public void doSomething() {
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?
We can use NumPy np. array tolist() function to convert an array to a list. If the array is multi-dimensional, a nested list is returned. For a one-dimensional array, a list with the array elements is returned.
There are multiple ways to convert an array to a list in C#. One method is using List. AddRange method that takes an array as an input and adds all array items to a List. The second method is using ToList method of collection.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With