Reputation: 269
I have a list as follow:
List<Integer> arrInt={2,3,5};
I want to convert this arraylist to array float.
float[] result={2,3,5};
My code:
public float[] convertIntToFloat(List<Integer> arr)
{
List<Float> arrResult=new ArrayList<Float>();
for(int i=0;i<arr.size();i++)
{
float x=i;
arrResult.add(x);
}
float result[]=arrResult.toArray( new float[arr.size()]); //Error
return result;
}
But it display error in my code as above. Can you help me?
Upvotes: 0
Views: 4590
Reputation: 7836
Do it like this:
public Float[] convertIntToFloat(List<Integer> arr)
{
List<Float> arrResult=new ArrayList<Float>();
for(int i=0;i<arr.size();i++)
{
float x=arr.get(i);
// float x=i; //Here you are retrieving index instead of value
arrResult.add(x);
}
Float result[] = arrResult.toArray( new Float[arr.size()]);
// float result[]=arrResult.toArray( new float[arr.size()]); //Error
return result;
}
Upvotes: 0
Reputation: 213351
List.toArray(T[])
takes an array for Wrapper type, not primitive type.
You should do it like this:
Float result[] = arrResult.toArray( new Float[arr.size()]);
But, that's really not required. Because, now you would have to convert this to primitive type array. That is too much right?
You can directly create a float[]
array, rather than going through an ArrayList<Float>
. Just change your arrResults
declaration to:
float[] arrResults = new float[arr.size()];
And in for loop, add elements to the array using:
for(int i = 0; i < arr.size(); ++i) {
arrResults[i] = arr[i];
}
Upvotes: 7
Reputation: 3773
Generic in Java is limited. You can't use (new float[]) as the parameter of toArray. Use (new Float[]) instead. However, in fact, a correct implement should be:
public float[] convertIntToFloat(List<Integer> arr)
{
float result = new float[arr.size()];
for(int i = 0; i < arr.size(); ++i)
{
result[i] = arr.get(i);
}
return result;
}
Upvotes: 0
Reputation: 2542
Just create the float
array directly:
public float[] convertIntToFloat(List<Integer> arr)
{
float[] arrResult = new float[arr.size()];
for(int i=0;i<arr.size();i++)
{
arrResult[i] = (float) arr[i];
}
return arrResult;
}
Upvotes: 0