You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LinkedList插入多矩阵仅存最后一个问题求助(附Java代码)

Why Only the Last Matrix is Added to Your LinkedList?

Hey there! Let's break down what's happening here and fix it.

The Root Cause

You're reusing the same Object[][] o array object for both matrices. In Java, arrays are reference types—when you add o to the LinkedList, you're not adding a copy of the array, just a reference pointing to the original array in memory.

So when you modify the elements of o the second time, you're overwriting the same array that the first entry in the LinkedList is pointing to. By the time you iterate through the list, both entries reference the exact same array, which holds only the last set of values you assigned.

The Fix: Create a New Array for Each Matrix

Instead of reusing the same array variable, create a brand new Object[][] instance every time you want to add a new matrix to the list. This way, each entry in the LinkedList points to a separate array with its own unique values.

Here's your updated code:

public LinkedList<Object[][]> addMatrices() { 
    LinkedList<Object[][]> l = new LinkedList<>(); 
    
    // First matrix: create a new array
    Object[][] firstMatrix = new Object[2][2]; 
    firstMatrix[0][0] = new Empty(2); 
    firstMatrix[0][1] = new Other(); 
    firstMatrix[1][0] = new Empty(4); 
    firstMatrix[1][1] = new Empty(6); 
    l.add(firstMatrix); 
    
    // Second matrix: create another new array
    Object[][] secondMatrix = new Object[2][2]; 
    secondMatrix[0][0] = new Empty(4); 
    secondMatrix[0][1] = new Other(); 
    secondMatrix[1][0] = new Empty(5); 
    secondMatrix[1][1] = new Empty(1); 
    l.add(secondMatrix); 
    
    // Iterate and print to verify
    for(Object[][] matrix : l) { 
        for(int i = 0; i < matrix.length; i++) {
            for(int j = 0; j < matrix[i].length; j++) {
                System.out.print(matrix[i][j] + " ");
            }
            System.out.println();
        }
        System.out.println("---");
    }
    return l;
}

Bonus: Clean Up Repeated Code

If you plan to add more matrices later, you can wrap the matrix creation in a helper method to avoid duplicate code:

// Helper method to create a 2x2 matrix
private Object[][] create2x2Matrix(Object topLeft, Object topRight, Object bottomLeft, Object bottomRight) {
    Object[][] matrix = new Object[2][2];
    matrix[0][0] = topLeft;
    matrix[0][1] = topRight;
    matrix[1][0] = bottomLeft;
    matrix[1][1] = bottomRight;
    return matrix;
}

Then use it like this:

l.add(create2x2Matrix(new Empty(2), new Other(), new Empty(4), new Empty(6)));
l.add(create2x2Matrix(new Empty(4), new Other(), new Empty(5), new Empty(1)));

This makes your code cleaner and less error-prone.

内容的提问来源于stack exchange,提问作者Ayoub Eloumari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:34:24