【问题标题】:Inserting different arrays in a ArrayList在 ArrayList 中插入不同的数组
【发布时间】:2017-03-21 16:01:13
【问题描述】:

我在 ArrayList 中插入了一个数组,但在插入第二个数组后,第一个数组与第二个数组相同。

主类:

public static void main(String[] args) {

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

    int[] parent = new int[4];

    for (int i = 0; i < 2; i++) {
        parent[0] = rand(4,1);
        parent[1] = rand(6, -2);
        parent[2] = rand(2, 1);
        parent[3] = rand(-1, -2);

        list.add(parent);
    }

    // to print the arrays of the parent
    for (int i = 0; i < 2; i++) {
        int[] arr ;
        arr = list.get(i);
        for (int j = 0; j < arr.length; j++) {
            System.out.println("Value "+arr[j]);
        }
        System.out.println("Next Array");
    }

Rand 函数 // 它是一个随机函数,在一个范围内生成随机值

public static int rand(int max,int min)
{
  Random rand = new Random();
  int value = 0;
  return value = rand.nextInt(max + 1 - min) + min; 
}

我已经运行了很多次,但是两个数组的值都是一样的。

Results

我不明白为什么要得到两个数组的相同值。

【问题讨论】:

  • parent的定义移动到for循环中。
  • 因为int[] 是一个对象,而不是原始值。您在列表中存储了两次相同的数组。
  • 那是因为第一次添加到列表中的对象与第二次添加的对象相同。因此,它在 for 循环的第二次迭代期间被修改并打印了两次。
  • @Thomas 准备因为说 pass-by-reference 而受到攻击。攻击在 3...2...1...

标签: java arrays arraylist


【解决方案1】:

把你的代码改成

for (int i = 0; i < 2; i++) {
    int[] parent = new int[4];
    parent[0] = rand(4,1);
    parent[1] = rand(6, -2);
    parent[2] = rand(2, 1);
    parent[3] = rand(-1, -2);

    list.add(parent);
}

否则,您将创建一个数组,设置其值,然后将其添加到列表中。然后,您将更改 same 数组的值并再次添加它。因此列表包含两次相同的数组。数组本身包含第二次迭代的随机数。

【讨论】:

    【解决方案2】:

    您将数组parent 添加到ArrayList 中,然后更改parent 的值,然后再次将其添加到ArrayList 中。 ArrayList 通过 reference 保存 int[],因此当您更改 parent 中的值时,您正在更改 list.get(0) 中的值

    每次添加到 ArrayList 时都需要创建一个新数组

    【讨论】:

      【解决方案3】:

      简单:

      int[] parent = new int[4];
      

      需要进入你的循环。

      否则,您会不断将 same 数组实例多次添加到该列表中。

      【讨论】:

        【解决方案4】:

        因为您将parent 数组的相同对象添加到您的ArrayList

        int[] parent = new int[4];
        
        for (int i = 0; i < 2; i++) {
            parent[0] = rand(4,1);
            parent[1] = rand(6, -2);
            parent[2] = rand(2, 1);
            parent[3] = rand(-1, -2);
        
            list.add(parent); // it's still the same object, but now twice in the arraylist
        }
        

        为了修复它,你可以像这样将它移到 for 循环中

        for (int i = 0; i < 2; i++) {
         int[] parent = new int[4];
         .....
        }
        

        您看到重复数组值的原因是它不是重复的,而是更像是在您的ArrayList 中可用两次的同一个数组。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-11-11
          • 1970-01-01
          • 2015-09-22
          • 2012-08-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-02-28
          相关资源
          最近更新 更多