java - 向 List 添加新元素会替换之前的元素

标签 java list arraylist

输出错误 这里我有 3 个列表“chkptPrice”、“fuelNeeded”和“motherList”。因此,在循环中,我将新元素添加到“chkptPrice”和“fuelNeeded”,然后将两个列表添加到“motherList”。当循环第一次运行时,一切都很顺利,但之后当我使用“chkptPrice”和“fuelNeeded”向“motherList”添加新元素时,整个列表将被相同的元素替换,并且元素会重复。

System.out.println("Enter the test cases");
    int tess = scan.nextInt();
    scan.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
    System.out.println("Enter the number of checkpoints: ");
    int checkpt = scan.nextInt();
    scan.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
    List<List<Integer>> motherList = new ArrayList<List<Integer>>();
    List<Integer> chkptPrice = new ArrayList<Integer>();
    List<Integer> fuelNeeded = new ArrayList<Integer>();

    for(int i=0; i<tess; i++)
    {
        chkptPrice.clear();
        fuelNeeded.clear();
        String[] price = scan.nextLine().split(" ");
        for(int j=0; j<checkpt; j++)
        {
            int intPrice = Integer.parseInt(price[j]);
            chkptPrice.add(intPrice);
        }
        String[] fueldist = scan.nextLine().split(" ");
        for(int j=0; j<checkpt; j++)
        {
            int intDist = Integer.parseInt(fueldist[j]);
            fuelNeeded.add(intDist);
        }
        System.out.println("Elements in chktPrice: "+chkptPrice);
        System.out.println("Elements in fuelNeeded: "+fuelNeeded);

        motherList.add(chkptPrice);
        motherList.add(fuelNeeded);



        System.out.println("Elements of motherList: "+motherList);
    }

====输入======

    2
    2
    1 3
    4 6
    4 9
    1 8

====输出======

{第一个循环}

    Elements in chktPrice: [1, 3]
    Elements in fuelNeeded: [4, 6]
    Elements of motherList: [[1, 3], [4, 6]]

{第二个循环}

    Elements in chktPrice: [4, 9]
    Elements in fuelNeeded: [1, 8]
    Elements of motherList: [[4, 9], [1, 8], [4, 9], [1, 8]]

motherList 元素应该是

[[1, 3], [4, 6], [4, 9], [1, 8]]

最佳答案

当您调用clear时,您并不是在创建新列表,而是删除已存在列表的内容(您清空了先前迭代中已添加的列表的内容)。

然后,当您在当前迭代中再次将它们添加到 motherList 时,您只需添加两个指向相同旧对象的新引用(因此最终有 4 个引用指向两个对象)。

要解决此问题,您必须重新初始化列表,而不是使用 clear

chkptPrice.clear(); -> chkptPrice = new LinkedList<>(); 
fuelNeeded.clear(); -> fuelNeeded = new LinkedList<>(); 

关于java - 向 List 添加新元素会替换之前的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52440419/

相关文章:

java - Mono.defer() 是做什么的?

c# - 对列表进行分组,并且仅当输入是列表时才获取不同的值

java - 如何在 Java 中创建匹配正则表达式的字符串数组列表?

java - float[]的ArrayList,无法检查ArrayList中是否包含float[]

java - 使用 vaadin 从数据库获取数据并显示在屏幕上

java - 使用 jms 连接到 ibm mq。指定 channel 和队列管理器

java - 有没有比在单个 JFrame 中保留多个 JTabbedPanes 更好的方法?

Python:项目的子列表取决于项目的某个值,例如 boolean 值

python 列表元素明智的条件增量

android - 如何使用两个 Firestore 集合制作一个 ArrayList?