how to create 2d arrazlist in java

how to create 2d arrazlist in java

To create a 2D ArrayList in Java, you can use the ArrayList class and nest it inside another ArrayList.

Here is an example of how you can create a 2D ArrayList in Java:

refer‮ot ‬:lautturi.com
ArrayList<ArrayList<Integer>> array = new ArrayList<>();

// Create the first row
ArrayList<Integer> row1 = new ArrayList<>();
row1.add(1);
row1.add(2);
row1.add(3);

// Create the second row
ArrayList<Integer> row2 = new ArrayList<>();
row2.add(4);
row2.add(5);
row2.add(6);

// Add the rows to the 2D ArrayList
array.add(row1);
array.add(row2);

This code creates a 2D ArrayList called array and adds two rows to it, each represented by a 1D ArrayList of integers. The first row contains the elements 1, 2, and 3, and the second row contains the elements 4, 5, and 6.

You can access and modify the elements of the 2D ArrayList using the get and set methods of the ArrayList class, and specifying the row and column indices.

Here is an example of how you can access and modify the elements of a 2D ArrayList in Java:

ArrayList<ArrayList<Integer>> array = new ArrayList<>();

// Create the first row
ArrayList<Integer> row1 = new ArrayList<>();
row1.add(1);
row1.add(2);
row1.add(3);

// Create the second row
ArrayList<Integer> row2 = new ArrayList<>();
row2.add(4);
row2.add(5);
row2.add(6);

// Add the rows to the 2D ArrayList
array.add(row1);
array.add(row2);

// Access the element at row 1, column 2
int element = array.get(1).get(2);

// Modify the element at row 0, column 1
array.get(0).set(1, 10);

This code creates a 2D ArrayList called array and adds two rows to it, as in the previous example. It then uses the get method to access the element at row 1, column 2, and stores it in a variable called element. It also uses the set method to modify the element at row 0, column 1, setting it to the value 10.

Note that the indices of the rows and columns in the 2D ArrayList start at 0, just like in a regular array.

Created Time:2017-11-01 12:05:15  Author:lautturi