Gurus, I have difficulty to pass an arraylist of doubly-linked list as a parameter.
I need to represent square matrices in data structure that involves linked-list. I decided to use an arraylist of doubly-linked list. Matrices information read from a text file, is stored in:
ArrayList<DoubleLinkedList<Integer>> dLLArrayList
After reads in the first input, dllArryList has content "[[5]]"
I try to create a new matrix object by calling the constructor from self-defined Matrix class:
Matrix mx1 = new Matrix (dimension, dLLArrayList);
** dimension is just an int variable that store the size of the matrix, say 1 for a 1 by 1 matrix, as indicated on the input text file.
However, as I try to print out the matrix content inside the Matrix class, it returns "[[]]":
System.out.println (this.getMatrixArrayList());
Here is the set method inside the matrix class that suppose to set ArrayList elements of a Matrix object:
public void setMatrixArrayList(ArrayList<DoubleLinkedList<Integer>> matrixArrayList) {
for(int i = 0; i < matrixArrayList.size(); i ++){
for (int j = 0; j < matrixArrayList.get(i).size(); j ++) {
this.rowItemList.add(matrixArrayList.get(i).get(j));
}
this.matrixArrayList.add(this.rowItemList);
this.rowItemList.clear();
}
}
Any reason this won’t work? Suggestions, Comments?
The problem is that you clear the rowItemList. When you add the rowItemList to the arraylist you just put the reference there. So when you clear it later the linkedlist just added inside the arraylist is also cleared. You need to clone the rowItemList when you add it in the outer list.