Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert object[][] to ArrayList<Object[]>

I think probably this question has been asked/answered several times before my post. But I couldn't get the exact thing I am looking for, so I post it again:

I am trying to do like this:

float[][] fa2 = {{7,2}, {5,4}, {9,6}, {4,7}, {8,1}, {2,3}};
ArrayList<Float[]> AF = new ArrayList<Float[]>();
AF = Arrays.asList(fa2);

But it is giving an error:

Type mismatch: cannot convert from List<float[]> to ArrayList<Float[]>

I understand the reason for the error but what is the most convenient way to do the conversion in Java ?

This is the easiest way that I can think of. Is there something better / more convenient ?

float[][] fa2 = {{7,2}, {5,4}, {9,6}, {4,7}, {8,1}, {2,3}};
ArrayList<Float[]> AF = new ArrayList<Float[]>(fa2.length);
for (float[] fa : fa2) {
    //initialize Float[]
    Float[] Fa = new Float[fa.length];
    //copy element of float[] to Float[]
    int i = 0;
    for (float f : fa) {
        Fa[i++] = Float.valueOf(f);
    }
    //add Float[] element to ArrayList<Float[]>
    AF.add(Fa);
}
like image 577
somnathchakrabarti Avatar asked Jan 13 '13 15:01

somnathchakrabarti


2 Answers

As you're converting from float[] to Float[] you have to do it manually:

float[][] fa2 = {{7,2}, {5,4}, {9,6}, {4,7}, {8,1}, {2,3}};
ArrayList<Float[]> AF = new ArrayList<Float[]>();
for(float[] fa: fa2) {
    Float[] temp = new Float[fa.length];
    for (int i = 0; i < temp.length; i++) {
        temp[i] = fa[i];
    }
    AF.add(temp);
}

Or you could just be using float[] all the way:

List<float[]> AF = Arrays.asList(fa2);
like image 92
Aleksander Blomskøld Avatar answered Sep 22 '22 06:09

Aleksander Blomskøld


This ran for me:

float[][] fa2 = {{7f,2f}, {5f,4f}, {9f,6f}, {4f,7f}, {8f,1f}, {2f,3f}};
List<float[]> AF = Arrays.asList(fa2); 

EDIT: If for some reason you MUST mix float[] and Float[] use Apache Commons ArrayUtils.toObject

float[][] fa2 = {{7f,2f}, {5f,4f}, {9f,6f}, {4f,7f}, {8f,1f}, {2f,3f}};
List<Float[]> AF = new ArrayList(fa2.length);
for (float[] fa : fa2) {
  AF.add(ArrayUtils.toObject(fa));
}
like image 32
HiJon89 Avatar answered Sep 21 '22 06:09

HiJon89