Skip to content
Advertisement

Creating a Matrix with ArrayLists

I want to create an ArrayList-matrix with n-rows and m-columns, for example

   1 2 3 4 5

   1 2 3 4 5 

   1 2 3 4 5

   1 2 3 4 5

   1 2 3 4 5

I’ve already written a code for creating such a matrix but my code doesn’t display the values when I clear the list containing the column-data. Here is my

package testproject;

import java.util.ArrayList;

public class TestProject {

    public static void main(String[] args) {
        ArrayList<Integer> intList = new ArrayList<>();
        ArrayList<ArrayList<Integer>> mainList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            for (int k = 0; k < 5; k++) {
                intList.add(k);
            }
            mainList.add(intList);
            intList.clear(); //this line is probably the problem
        }
        for (int row = 0; row < mainList.size(); row++) {
            for (int col = 0; col < mainList.get(0).size(); col++) {
                System.out.print(mainList.get(row).get(col) + ",");
            }
            System.out.println("");
        }
    }
}

Is there any possibility to clear the contents of intList without clearing the contents of mainList??

Advertisement

Answer

When calling mainList.add(intList); you are adding a reference pointing to the intList object into your mainList rather than copying the values. You will have to create one instance of “intList” per row, and not clear anything.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement