Reputation: 3086
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);
}
Upvotes: 5
Views: 2823
Reputation: 18542
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);
Upvotes: 6
Reputation: 535
Another way you could do this:
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))
I forgot to add the cast.. fixed it.
Upvotes: 1
Reputation: 911
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));
}
Upvotes: 2
Reputation: 135992
try
float[][] fa2 = {{7,2}, {5,4}, {9,6}, {4,7}, {8,1}, {2,3}};
List<float[]> af = Arrays.asList(fa2);
or
Float[][] fa2 = {{7f,2f}, {5f,4f}, {9f,6f}, {4f,7f}, {8f,1f}, {2f,3f}};
List<Float[]> af = Arrays.asList(fa2);
Upvotes: 0
Reputation: 602
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).
Upvotes: 0