I have to create a 2d array with unknown size. So I have decided to go with a 2d ArrayList the problem is I'm not sure how to initialize such an array or store information.
Say I have the following data
0 connects 1
2 connects 3
4 connects 5
....etc up to a vast amount of random connections
and I want to insert
true(1) into [0][1],
true(1) into [2][3],
true(1) into [4][5].
Can the array automatically update the column/rows for me
Any help is appreciated thanks
<ArrayList_name>. add(Object element) : It helps in adding a new row in our existing 2D arraylist where element is the element to be added of datatype of which ArrayList created. <ArrayList_name> . add(int index, Object element) : It helps in adding the element at a particular index.
Elements can be filled in a Java double array in a specified range using the java. util. Arrays. fill() method.
I'm not sure how to initialize such an array or store information.
Like this for instance:
List<List<Integer>> twoDim = new ArrayList<List<Integer>>();
twoDim.add(Arrays.asList(0, 1, 0, 1, 0));
twoDim.add(Arrays.asList(0, 1, 1, 0, 1));
twoDim.add(Arrays.asList(0, 0, 0, 1, 0));
or like this if you prefer:
List<List<Integer>> twoDim = new ArrayList<List<Integer>>() {{
add(Arrays.asList(0, 1, 0, 1, 0));
add(Arrays.asList(0, 1, 1, 0, 1));
add(Arrays.asList(0, 0, 0, 1, 0));
}};
To insert a new row, you do
twoDim.add(new ArrayList<Integer>());
and to append another element on a specific row
you do
twoDim.get(row).add(someValue);
Here is a more complete example:
import java.util.*;
public class Test {
public static void main(String[] args) {
List<List<Integer>> twoDim = new ArrayList<List<Integer>>();
String[] inputLines = { "0 1 0 1 0", "0 1 1 0 1", "0 0 0 1 0" };
for (String line : inputLines) {
List<Integer> row = new ArrayList<Integer>();
Scanner s = new Scanner(line);
while (s.hasNextInt())
row.add(s.nextInt());
twoDim.add(row);
}
}
}
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