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.
Your example looks like you want to have a map from pairs of ints to booleans (with the default value being false). If this is a sparse map (i.e. really most of the positions are false), you may be better with something like a HashSet or similar (with being a class encapsulating two ints with a suitable implementation of hashCode and equals).
class IntPair {
int first;
int second;
public boolean equals(Object o) {
return o instanceof IntPair &&
((IntPair)o).first == first &&
((IntPair)o).second == second;
}
/** optimized for small numbers */
public int hashCode() {
return first + second * 44729;
}
public String toString() {
return "(" + first + ", " + second + ")";
}
}
Then, to say "0 connects 1" you would write
set.add(new IntPair(0,1));
It really depends on what operations you want to use afterwards - such a HashSet has quick lookup and change and uses not too much space, but you can't get quickly "all neighbours of node 1". If you need such access, you may simply want a class like
class Node {
int id;
Set<Node> neighbours;
}
and additionally a list/array/set of such nodes.
The question "array of unknown size" is not specific enough to really answer competently.
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);
}
}
}