With this post I just want to show how to convert a Java collection into an array and how to convert a wrapper class array into an array of the corresponding primitive data type. As a bonus I will show how to iterate over an ArrayList.
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
| public static void main(String[] args)
{
// Java collection (ArrayList) with Floats
ArrayList<Float> someFloats = new ArrayList<Float>();
someFloats.add(3.72f);
someFloats.add(28.07f);
someFloats.add(2011f);
// Convert ArrayList into an array
Float[] floatWrapperArray = someFloats.toArray(new Float[someFloats.size()]);
float[] floatArray = new float[floatWrapperArray.length];
// Transfer array of Wrapper type (Float) into array of primitive data type (float)
for (int i = 0; i < floatArray.length; i++)
{
floatArray[i] = floatWrapperArray[i].floatValue();
}
// 1. Float ArrayList
System.out.println("1. Float ArrayList");
for (Iterator iterator = someFloats.iterator(); iterator.hasNext();)
{
Float currentFloat = (Float) iterator.next();
System.out.println(currentFloat);
}
// 2. Float array
System.out.println("2. Float array");
for (int i = 0; i < floatWrapperArray.length; i++)
{
System.out.println(floatWrapperArray[i]);
}
// 3. float array
System.out.println("3. float array");
for (int i = 0; i < floatArray.length; i++)
{
System.out.println(floatArray[i]);
}
} |
public static void main(String[] args)
{
// Java collection (ArrayList) with Floats
ArrayList<Float> someFloats = new ArrayList<Float>();
someFloats.add(3.72f);
someFloats.add(28.07f);
someFloats.add(2011f);
// Convert ArrayList into an array
Float[] floatWrapperArray = someFloats.toArray(new Float[someFloats.size()]);
float[] floatArray = new float[floatWrapperArray.length];
// Transfer array of Wrapper type (Float) into array of primitive data type (float)
for (int i = 0; i < floatArray.length; i++)
{
floatArray[i] = floatWrapperArray[i].floatValue();
}
// 1. Float ArrayList
System.out.println("1. Float ArrayList");
for (Iterator iterator = someFloats.iterator(); iterator.hasNext();)
{
Float currentFloat = (Float) iterator.next();
System.out.println(currentFloat);
}
// 2. Float array
System.out.println("2. Float array");
for (int i = 0; i < floatWrapperArray.length; i++)
{
System.out.println(floatWrapperArray[i]);
}
// 3. float array
System.out.println("3. float array");
for (int i = 0; i < floatArray.length; i++)
{
System.out.println(floatArray[i]);
}
}
Output
1
2
3
4
5
6
7
8
9
10
11
12
| 1. Float ArrayList
3.72
28.07
2011.0
2. Float array
3.72
28.07
2011.0
3. float array
3.72
28.07
2011.0 |
1. Float ArrayList
3.72
28.07
2011.0
2. Float array
3.72
28.07
2011.0
3. float array
3.72
28.07
2011.0