Re: Creating 2 D arraylist
maralfarshadi@yahoo.com wrote:
Could you please explain or refer some reading material on how to
create two dimensional array lists ? and how to access the fields with
columns and row indexes ?
There is no such think like "two dimensional array list" in Java.
However, the List of Lists may bey used as closest equivalent of two
dimensional Java arrays.
See the following example:
import java.util.*;
public class TwoDiALExample {
static <T> ArrayList<List<T>> create2DArrayList(
int rows, int columns, T init) {
ArrayList<List<T>> list = new ArrayList<List<T>>();
for(int r = 0; r < rows; ++r) {
list.add(new ArrayList<T>(
Collections.nCopies(columns, init)));
}
return list;
}
public static void main(String[] args) {
List<List<Integer>> twodial
= create2DArrayList(3, 3, 0);
twodial.get(1).set(1, 1);
System.out.println(twodial);
}
}
When the number of your columns is fixed, you may also use a single
array list, and compute each element's index using the following formula:
listIndex = row * columnWidth + column
Alternatively, consider using a Map (most likely HashMap, or TreeMap)
with a keys made of row, and column pairs. It likely would not be as
fast as array list based variant, but allows to achieve fully dynamic
equivalent of two-dimensional indexed structure.
HTH,
piotr