简体   繁体   English

数组列表 <Integer[]> 在Java中不起作用

[英]ArrayList<Integer[]> not working in java

I want to make an arraylist with int[] as objects 我想用int[]作为对象创建一个arraylist

ArrayList<Integer[]> b= new ArrayList<Integer[]>();
    Integer[] a= new Integer[2];
    for(Integer i=0;i<20;i++){
        a[0]=i;
        a[1]=i;
        b.add(a);
    }
    for(int i=0;i<20;i++){
        System.out.println("line"+i+"= "+b.get(i)[0]+" "+b.get(i)[1]);
    }

and the result I get is this 我得到的结果是

在此处输入图片说明

instead of the values( 0 0 1 1 etc), is seems that has saved only the last. 而不是值(0 0 1 1等),似乎只保存了最后一个。 I have also tried with type int instead of Integer but the same result 我也尝试过使用int类型而不是Integer但结果相同

Consider initializing a within the loop as otherwise you are just writing over the same array the whole time. 考虑在循环内初始化a ,否则您将一直在同一数组上进行写入。 Instead of 代替

ArrayList<Integer[]> b= new ArrayList<Integer[]>();
    Integer[] a= new Integer[2];
    for(Integer i=0;i<20;i++){
        a[0]=i;
        a[1]=i;
        b.add(a);
    }
    for(int i=0;i<20;i++){
        System.out.println("line"+i+"= "+b.get(i)[0]+" "+b.get(i)[1]);
    }

consider this: 考虑一下:

ArrayList<Integer[]> b= new ArrayList<Integer[]>();
    for(Integer i=0;i<20;i++){
        Integer[] a= new Integer[2];
        a[0]=i;
        a[1]=i;
        b.add(a);
    }
    for(int i=0;i<20;i++){
        System.out.println("line"+i+"= "+b.get(i)[0]+" "+b.get(i)[1]);
    }

As the point is for each loop iteration to make a new array and store new values rather than overwrite the existing ones as if you step through your code you may notice you how don't ever allocate a new array within the loop. 关键是每次循环迭代都需要创建一个新数组并存储新值,而不是覆盖现有值,就像您逐步执行代码一样,您可能会注意到您从未在循环内分配新数组。

You have to declare a new array for each element you're going to add. 您必须为要添加的每个元素声明一个新数组。 Otherwise they all reference the same memory. 否则,它们都引用相同的内存。 Declare the array inside the for loop instead of before the loop. 在for循环中而不是循环之前声明数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM