You seem to think you have a 2-D matrix of numbers, stored as an ArrayList
. That is not what you have at all. Instead, you have a 2-D matrix where each element is an ArrayList
. That means you really have 3 dimensions represented in your code. I don't think that's what you want. There are several ways you could achieve two dimensions using the constructs you already have (i.e. without going to some external library).
A 2-D array of numbers
The array is an easy to understand construct, so let's start with that.
Number[][] table = new Number[10][10];
table[0][0] = 0;
table[0][1] = 10;
table[1][0] = 20;
table[1][1] = 30;
System.out.println("Value="+table[1][0].get());
This code declares a 2-D array of type Number
, then initializes it with 10 rows and 10 columns. It then partially fills in numbers. As long as you access an element that has already been initialized, you'll be ok. Trying to access an element that hasn't yet been initialized (like table[3][4]
) would be bad.
Another way to initialize an array
Number[][] table = { { 0, 10 }, { 20, 30 } };
System.out.println("Value=" + table[1][0]);
This is the same thing as before, but initialized all at once. This particular array only has 2 rows and 2 columns.
Nested ArrayLists
If you want to use an ArrayList
instead of an array, that's fine. You just need to realize that the ArrayList
actually will contain other ArrayLists
, each of which will contain Numbers
. Like so:
ArrayList<ArrayList<Number>> table = new ArrayList<>();
table.add(new ArrayList<>());
table.add(new ArrayList<>());
table.get(0).add(0);
table.get(0).add(10);
table.get(1).add(20);
table.get(1).add(30);
System.out.println("Value=" + table.get(1).get(0));
In this example, you first declare an ArrayList
that contains ArrayLists
that contain Numbers
, and initialize the outer ArrayList
. Then you create some inner ArrayLists
, and finally give each of them some Numbers
.
Summary
You can use arrays or ArrayLists
as you prefer. You just have to initialize them correctly before accessing their elements. How to initialize depends on the data structure you choose.
All the codes
import java.util.ArrayList;
public class TwoD {
public void example1() {
Number[][] table = new Number[10][10];
table[0][0] = 0;
table[0][1] = 10;
table[1][0] = 20;
table[1][1] = 30;
System.out.println("\nExample 1");
System.out.println("Value=" + table[1][0]);
}
public void example2() {
Number[][] table = { { 0, 10 }, { 20, 30 } };
System.out.println("\nExample 2");
System.out.println("Value=" + table[1][0]);
}
public void example3() {
ArrayList<ArrayList<Number>> table = new ArrayList<>();
table.add(new ArrayList<>());
table.add(new ArrayList<>());
table.get(0).add(0);
table.get(0).add(10);
table.get(1).add(20);
table.get(1).add(30);
System.out.println("\nExample 3");
System.out.println("Value=" + table.get(1).get(0));
}
public static void main(String[] args) {
TwoD me = new TwoD();
me.example1();
me.example2();
me.example3();
}
}