Question

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?

Was it helpful?

Solution

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];
}

OTHER TIPS

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

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

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;
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top