Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transform array to list

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?

like image 442
Jakub Avatar asked Sep 28 '11 14:09

Jakub


People also ask

Can you convert an array to a list in Python?

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.

Can you convert array to list C#?

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.


3 Answers

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.

like image 131
JB Nizet Avatar answered Oct 09 '22 02:10

JB Nizet


[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.

like image 37
Ed Staub Avatar answered Oct 09 '22 01:10

Ed Staub


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

like image 2
Kevin Bourrillion Avatar answered Oct 09 '22 01:10

Kevin Bourrillion