Java中LinkedList仅添加尾节点及矩阵修改插入链表问题
Hey there! Let's tackle your two Java challenges one by one, with practical, actionable solutions:
1. Implement adding only the last node to LinkedList
Your requirement can mean two common scenarios—let's cover both:
Scenario A: Keep only the latest element in the list
If you want the LinkedList to always hold just the most recent matrix (discarding all previous entries when a new one is added), use this straightforward approach:
LinkedList<Object[][]> matrixList = new LinkedList<>(); public void addOnlyLatestMatrix(Object[][] newMatrix) { // Clear all existing elements first matrixList.clear(); // Add the new matrix as the only element at the tail matrixList.addLast(newMatrix); }
Scenario B: Allow multiple elements but only insert at the tail
If you want to build a list where new elements are always appended to the end (no middle/head inserts), just stick to addLast() and avoid methods like addFirst() or add(int index, E):
public void addMatrixToTail(Object[][] newMatrix) { matrixList.addLast(newMatrix); }
2. Fix the duplicate object reference issue with matrices
The root problem here is that Java arrays are reference types. When you add this.k directly to the LinkedList, you're storing a pointer to the original matrix—not a copy. So any changes to this.k will affect every entry in the list that points to it.
To fix this, you need to create a deep copy of the matrix before adding it to the list. Here's how to do it properly:
Step 1: Make your custom classes copyable
First, ensure Empty, Neutral, and Other support copying. The easiest way is to implement the Cloneable interface and override clone():
class Empty implements Cloneable { private Object value; public Object getValue() { return value; } public void setValue(Object value) { this.value = value; } @Override protected Empty clone() throws CloneNotSupportedException { // For simple classes with no nested reference-type fields, super.clone() works return (Empty) super.clone(); // If your class has nested references, you'll need to clone those manually here } } // Repeat the same Cloneable implementation for Neutral and Other classes
Step 2: Create a deep copy method for the matrix
This method will create a full copy of the matrix, including copying each custom element:
private Object[][] deepCopyMatrix(Object[][] original) { if (original == null) return null; Object[][] copiedMatrix = new Object[original.length][]; for (int row = 0; row < original.length; row++) { copiedMatrix[row] = new Object[original[row].length]; for (int col = 0; col < original[row].length; col++) { Object element = original[row][col]; // Clone custom elements if they're Cloneable if (element instanceof Cloneable) { try { copiedMatrix[row][col] = ((Cloneable) element).getClass() .getMethod("clone") .invoke(element); } catch (Exception e) { e.printStackTrace(); // Fallback to original element if cloning fails (adjust as needed) copiedMatrix[row][col] = element; } } else { // For immutable types (like String, Integer) or primitives, direct assignment is safe copiedMatrix[row][col] = element; } } } return copiedMatrix; }
Step 3: Insert the copied matrix into the LinkedList
Now update your logic to use the deep copy before adding to the list:
// Modify a specific position in the original matrix public void updateMatrix(int targetRow, int targetCol, Object newElement) { if (targetRow >= 0 && targetRow < this.k.length && targetCol >= 0 && targetCol < this.k[targetRow].length) { this.k[targetRow][targetCol] = newElement; } } // Add a copy of the matrix to the LinkedList public void addMatrixToList() { Object[][] matrixCopy = deepCopyMatrix(this.k); // Use whichever add method fits your first requirement (from section 1) matrixList.addLast(matrixCopy); // OR: addOnlyLatestMatrix(matrixCopy); }
With this setup, every entry in your LinkedList is an independent copy of the matrix. Changing the original this.k or any matrix in the list won't affect the others.
内容的提问来源于stack exchange,提问作者Ayoub Eloumari

