I am new to Java and trying to create a 2d list the size of which isn't fixed.I have a class which looks like this:
public class q1 {
List<List<Integer> > L = new ArrayList<List<Integer> >();
public void set(int m,int n){
//This is the function which would get the size of the 2d list
}
}
I saw the answers but they had to be of fixed sizes, eg:
ArrayList<String>[][] list = new ArrayList[10][10];
But, I want different sizes of the list L for different objects. There were other options like copyOf, but can the above functionality be achieved just by this array?
You are mixing two things in your question, ArrayLists and arrays. ArrayList is a variable size container backed by an array. ArrayList has a constructor where you can specify the initial capacity you need so with ArrayLists it will look like:
public class q1 {
List<List<Integer>> L;
public void set(int m, int n){
L = new ArrayList<>(m); // assuming m is the number or rows
for(int i = 0; i < m; ++i) {
L.add(new ArrayList<>(n));
}
// now you have a List of m lists where each inner list has n items
}
}
With arrays, the syntax is slightly different:
public class q1 {
Integer[][] L;
public void set(int m, int n){
L = new Integer[m][]; // assuming m is the number or rows
for(int i = 0; i < m; ++i) {
L[i] = new Integer[n];
}
// now you have a array of m arrays where each inner array has n items
}
}
Moreover if all the inner arrays will have the same length (n) the set method could be simplified to:
public void set(int m, int n){
L = new Integer[m][n]; // assuming m is the number or rows
// now you have a array of m arrays where each inner array has n items
}
There's no such special syntax for Lists, but you could always just iterate over the number of smaller lists and initialize them individually. Note that passing the size to the ArrayList's constructor doesn't really set its size, but it is does allocate the space, and may save you rellocations in the future:
public void set(int m,int n){
l = new ArrayList<>(m);
for (int i = 0; i < m; ++i) {
l.add(new ArrayList<>(n));
}
}
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