2016-01-20 83 views
-3

我需要创建一个ArrayList来收集某些点的位置。如何在Java中添加更改变量元素到ArrayList

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

当我尝试显示集合,所有元素中是完全一样的最后一个加入(在这种情况下:[C,d])

如何添加元素到我的ArrayList在这种情况下适当?非常感谢您

+0

做到这一点我不知道add()方法只集合链接元素的地址,所以我的所有元素都链接到同一个东西。如果我希望集合保存每个元素内的值,我该怎么做。 –

+0

您不需要创建或重新定义'location' int数组。只要调用'collection.add({a,b});''''和'collection.add({c,d});' –

+0

嗨,那句话是错误的。我试过,但它不起作用 –

回答

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

其实我建议你封装你的位置作为一个POJO,为了更好的灵活性和可用性。

-1

您需要创建一个新的数组备考每对coirdinates的添加到ArrayList

-1

您可以轻松地

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

是不是正确的语法'new int [] {a,b}'? –

+0

我也这么认为,但不知怎的,这种语法不起作用。我认为ArrayList声明在这里是错误的 –

+0

@MickMnemonic出于某种原因,我认为'new int []'在这个语法中不是必需的,但我可以明白为什么会这样。我会相应地更新答案。 –

相关问题