I want to create a two dimensional array dynamically.
I know the number of columns. But the number of rows are being changed dynamically. I tried the array list, but it stores the value in single dimension only. What can I do?
String [][] stringArray = allocate(String. class,3,3); This will give you a two dimensional String array with 3 rows and 3 columns; Note that in Class<tType> c -> c cannot be primitive type like say, int or char or double . It must be non-primitive like, String or Double or Integer and so on.
A 2D array can be dynamically allocated in C using a single pointer. This means that a memory block of size row*column*dataTypeSize is allocated using malloc and pointer arithmetic can be used to access the matrix elements.
Any 2-dimensional array can be declared as follows: data_type: Since Java is a statically-typed language (i.e. it expects its variables to be declared before they can be assigned values).
Initialization of 2-D array in Java: 1 no_of_rows: The number of rows an array can store. e.g. no_of_rows = 3, then the array will have three rows. 2 no_of_columns: The number of rows an array can store. e.g. no_of_columns = 4, then the array will have four columns. More ...
Here, the concept of dynamic array comes into existence. It expends the size of the array dynamically. In this section, we will understand what is a dynamic array, features of the dynamic array, how to resize a dynamic array, and how to implement dynamic array in Java.
Similarly, a two-dimensional array is an array which technically has one row of elements, however, each row has a bunch of elements defined by itself. Basically, you need to define both the rows and columns and then go ahead with declaring the elements in the respective locations or indexes.
Since the number of columns is a constant, you can just have an List
of int[]
.
import java.util.*; //... List<int[]> rowList = new ArrayList<int[]>(); rowList.add(new int[] { 1, 2, 3 }); rowList.add(new int[] { 4, 5, 6 }); rowList.add(new int[] { 7, 8 }); for (int[] row : rowList) { System.out.println("Row = " + Arrays.toString(row)); } // prints: // Row = [1, 2, 3] // Row = [4, 5, 6] // Row = [7, 8] System.out.println(rowList.get(1)[1]); // prints "5"
Since it's backed by a List
, the number of rows can grow and shrink dynamically. Each row is backed by an int[]
, which is static, but you said that the number of columns is fixed, so this is not a problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With