i want to create two dimensional array dynamically.I know the number of columns.But the number of rows are changed dynamically.I try the array list,but it stores the value in single dimension only.what can i do?
+1
A:
How about making a custom class containing an array, and use the array of your custom class.
KMan
2010-04-25 06:26:15
+1
A:
There are no multi-dimensional arrays in Java, there are, however, arrays of array.
Just make an array of however large you want, then for each element make another array however large you want that one to be.
int array[][];
array = new int[10][];
array[0] = new int[9];
array[1] = new int[8];
array[2] = new int[7];
array[3] = new int[6];
array[4] = new int[5];
array[5] = new int[4];
array[6] = new int[3];
array[7] = new int[2];
array[8] = new int[1];
array[9] = new int[0];
Alternatively:
List<Integer>[] array;
array = new List<Integer>[10];
// of you can do "new ArrayList<Integer>(the desired size);" for all of the following
array[0] = new ArrayList<Integer>();
array[1] = new ArrayList<Integer>();
array[2] = new ArrayList<Integer>();
array[3] = new ArrayList<Integer>();
array[4] = new ArrayList<Integer>();
array[5] = new ArrayList<Integer>();
array[6] = new ArrayList<Integer>();
array[7] = new ArrayList<Integer>();
array[8] = new ArrayList<Integer>();
array[9] = new ArrayList<Integer>();
TofuBeer
2010-04-25 06:32:30
+2
A:
Since the number of columns is a constant, you can just have an List
of int[]
.
import java.util.*;
//...
List<int[]> rowList = new ArrayList<int[]>();
rowList.add(new int[] { 1, 2, 3 });
rowList.add(new int[] { 4, 5, 6 });
rowList.add(new int[] { 7, 8 });
for (int[] row : rowList) {
System.out.println("Row = " + Arrays.toString(row));
} // prints:
// Row = [1, 2, 3]
// Row = [4, 5, 6]
// Row = [7, 8]
System.out.println(rowList.get(1)[1]); // prints "5"
Since it's backed by a List
, the number of rows can grow and shrink dynamically. Each row is backed by an int[]
, which is static, but you said that the number of columns is fixed, so this is not a problem.
polygenelubricants
2010-04-25 06:53:40