Omicron
Omicron

Reputation: 64

How to add Array to ArrayList (Java)

I have a global ArrayList list declared with the intention of adding a float variable to it in a method:

ArrayList<Float[]> list = new ArrayList<Float[]>();

Here is the method:

public void recieve(float[] coords)
{
    this.list.add(?); 
}

What is the syntax for adding coords to the ArrayList?

Upvotes: 0

Views: 470

Answers (3)

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 236122

You're looking for this:

public void receive(float[] coords) { // fixed misspelling in name
    Float[] fCoords = new Float[coords.length];
    for (int i = 0; i < coords.length; i++)
        fCoords[i] = coords[i];       // autoboxing takes place here
    this.list.add(fCoords); 
}

Because the ArrayList expects a Float[], but you have a float[] as parameter (notice the difference in letter case!) a manual conversion is required before adding it to the list.

Upvotes: 2

Blub
Blub

Reputation: 3822

You will have to convert it manually I think.

public void recieve(float[] coords) {
   this.list.add(convertToFloat(coords));
}

public Float[] convertToFloat(float[] coords) {
  Float[] converted = new Float[coords.length];
  for (int i = 0; i < coords.length; i++) {
     converted[i] = Float.valueOf(coords[i]));
  }
  return converted;
}

Upvotes: 4

REALFREE
REALFREE

Reputation: 4406

Since you declare Arraylist type as float array, I believe you can just use as

list.add(coords);

Cheers

Upvotes: 0

Related Questions