-3

I have a need create an ArrayList to collect positions of some points.

ArrayList<int[]>  collection =  new ArrayList<int[]> ;
//the position has 2 coordinations. 
int[] location = new int[2]
//add first position a,b
location[0] = a;
location[1] = b;
collection.add(location);
//add second position c,d
location[0] = c;
location[1] = d;
collection.add(location);

When I try to display the collection, all the elements inside are exactly the same as the last one was added (in this case: [c,d])

How do I add the element to my ArrayList properly in this case ? Thank you very much

3
  • I wonder if the add() method only link the collection to the address of the element, so all of my elements was linked to the same thing. What do I do if I want the collection to save the values inside of each elements. Commented Jan 20, 2016 at 2:48
  • You don't need to create or redefine location int array. Just call collection.add({a,b}); and collection.add({c,d}); Commented Jan 20, 2016 at 2:48
  • Hi, that syntax is wrong. I tried that but it doesn't work Commented Jan 20, 2016 at 3:00

3 Answers 3

-1
  ArrayList<int[]>  collection =  new ArrayList<int[]> ;
  //the position has 2 coordinations. 
  int[] location = new int[2]
  //add first position a,b
  location[0] = a;
  location[1] = b;
  collection.add(location);
  //add second position c,d
  location = new int[2]; //<-here
  location[0] = c;
  location[1] = d;
  collection.add(location);

Actually i would recommend you encapsulate your location as a POJO, for better flexibility and usability.

Sign up to request clarification or add additional context in comments.

Comments

-1

You need to create a new array forma each pair of coirdinates you add to the ArrayList

Comments

-1

You can accomplish this easily with

collection.add(new int[]{a,b});
collection.add(new int[]{c,d});

4 Comments

Isn't the correct syntax new int[]{a, b}?
I thought so too but somehow this syntax doesn't work. I think the ArrayList declaration is in the wrong here
@MickMnemonic For some reason I was thinking new int[] was not required in this syntax, but I can see why it would be. I'll update the answer accordingly.
oh the new int[]{a, b} worked, thank you very much !

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.