简体   繁体   中英

Create a 2d Linked List in Java

I created a 2d linked list in java. I used for-loop in building it to make my desired rows and columns, however as I add the row, the column also adds. The number of desired rows and columns does not work well. This is my code:

public class BoardClass{
    public LinkedList<LinkedList<Integer>> empiBoard = new LinkedList<LinkedList<Integer>>();
    public LinkedList<Integer> rowList = new LinkedList<Integer>();


public LinkedList<LinkedList<Integer>> createBoard (int col, int row){
    for(int i=0; i<row; i++) {
        for(int j=0; j<col; j++) {
            rowList.add(0); 
        }
        empiBoard.add(rowList);

    }
    return empiBoard;
}

}

You need a different type of structure.

public class BoardClass{
    public List<List<Integer>> emptyBoard = null;


public List<List<Integer>> createBoard (int col, int row){
    emptyBoard = new ArrayList<List<Integer>>(row);
    for(int i=0; i<row; i++) {
        List<Integer> rowList = new ArrayList(col)
        for(int j=0; j<col; j++) {
            rowList.add(0); 
        }
        emptyBoard.add(rowList);

    }
    return empiBoard;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM