5

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);
}
4

5 回答 5

6

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);
于 2013-01-13T15:34:23.280 回答
2

这为我跑了:

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

编辑:如果由于某种原因您必须混合使用 float[] 和 Float[] 使用 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));
}
于 2013-01-13T15:38:58.347 回答
1

您可以这样做的另一种方法:

    float[][] fa2 = {{7,2}, {5,4}, {9,6}, {4,7}, {8,1}, {2,3}};

   ArrayList<float[]> AF = new ArrayList<float[]>((Collection<float[]>)Arrays.asList(fa2))

我忘了添加演员表..修复它。

于 2013-01-13T15:40:52.920 回答
0

You can just do it like this and you don't need to convert:

Float[][] test = {{2f,3f},{3f,4f}};

The concept that allows to wrap the natives in Java to change into Objects is called AutoBoxing, which is being used here. However, for this to work you either have to specifically say that the numbers are floats or cast them with (float).

于 2013-01-13T15:35:42.080 回答
0

尝试

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

或者

Float[][] fa2 = {{7f,2f}, {5f,4f}, {9f,6f}, {4f,7f}, {8f,1f}, {2f,3f}};
List<Float[]> af = Arrays.asList(fa2);
于 2013-01-13T15:40:36.120 回答