【问题标题】:How to Add Changing Variable Element to ArrayList in Java [duplicate]如何在 Java 中将更改的变量元素添加到 ArrayList [重复]
【发布时间】:2016-01-20 02:43:53
【问题描述】:

我需要创建一个 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 中?非常感谢

【问题讨论】:

  • 我想知道 add() 方法是否只将集合链接到元素的地址,所以我的所有元素都链接到同一个东西。如果我希望集合保存每个元素内部的值,我该怎么办。
  • 您不需要创建或重新定义location int 数组。只需致电collection.add({a,b});collection.add({c,d});
  • 您好,语法错误。我试过了,但它不起作用

标签: java arrays arraylist element


【解决方案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,以获得更好的灵活性和可用性。

【讨论】:

    【解决方案2】:

    您需要为添加到 ArrayList 的每对坐标创建一个新的数组格式

    【讨论】:

      【解决方案3】:

      你可以很容易地做到这一点

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

      【讨论】:

      • 语法不正确new int[]{a, b}
      • 我也是这么想的,但不知何故这种语法不起作用。我认为这里的 ArrayList 声明是错误的
      • @MickMnemonic 出于某种原因,我认为new int[] 在这种语法中不是必需的,但我知道为什么会这样。我会相应地更新答案。
      • 哦,新的 int[]{a, b} 工作了,非常感谢!
      猜你喜欢
      • 1970-01-01
      • 2011-01-27
      • 1970-01-01
      • 1970-01-01
      • 2017-03-11
      • 1970-01-01
      • 2020-07-23
      • 1970-01-01
      相关资源
      最近更新 更多