How to Dynamically Build a Multi-Dimensional Array in Java

Is it possible to dynamically build a multi-dimensional array in Java?

It is actually possible to do in java. (I'm a bit surprised I must say.)

Disclaimer; I never ever want to see this code anywhere else than as an answer to this question. I strongly encourage you to use Lists.

import java.lang.reflect.Array;
import java.util.*;

public class Test {

public static int[] tail(int[] arr) {
return Arrays.copyOfRange(arr, 1, arr.length);
}

public static void setValue(Object array, String value, int... indecies) {
if (indecies.length == 1)
((String[]) array)[indecies[0]] = value;
else
setValue(Array.get(array, indecies[0]), value, tail(indecies));
}

public static void fillWithSomeValues(Object array, String v, int... sizes) {
for (int i = 0; i < sizes[0]; i++)
if (sizes.length == 1)
((String[]) array)[i] = v + i;
else
fillWithSomeValues(Array.get(array, i), v + i, tail(sizes));
}

public static void main(String[] args) {

// Randomly choose number of dimensions (1, 2 or 3) at runtime.
Random r = new Random();
int dims = 1 + r.nextInt(3);

// Randomly choose array lengths (1, 2 or 3) at runtime.
int[] sizes = new int[dims];
for (int i = 0; i < sizes.length; i++)
sizes[i] = 1 + r.nextInt(3);

// Create array
System.out.println("Creating array with dimensions / sizes: " +
Arrays.toString(sizes).replaceAll(", ", "]["));
Object multiDimArray = Array.newInstance(String.class, sizes);

// Fill with some
fillWithSomeValues(multiDimArray, "pos ", sizes);

System.out.println(Arrays.deepToString((Object[]) multiDimArray));

}
}

Example Output:

Creating array with dimensions / sizes: [2][3][2]
[[[pos 000, pos 001], [pos 010, pos 011], [pos 020, pos 021]],
[[pos 100, pos 101], [pos 110, pos 111], [pos 120, pos 121]]]

how to create dynamic two dimensional array in java?

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.

How to dynamically build multiple dimensional array in Java?

Example of dynamic multi-dimensional array creation:

String input = "5 2 2 3 2 2";
Scanner sc = new Scanner(input);
int dimCount = sc.nextInt();
int[] dims = new int[dimCount];
for (int i = 0; i < dimCount; i++)
dims[i] = sc.nextInt();
Object multiDimArray = java.lang.reflect.Array.newInstance(int.class, dims);

Now you just need to keep using java.lang.reflect.Array to manipulate it, since you don't know at compile-time how many dimensions it has.

how to create multi dimensional array dynamic in java?

I believe that what you want to do is this:

// Create a 2D array of length of 5
int[][] args = new int[5][];
// Iterate from 0 to 4
for(int k=0;k<5;k++){
// Affect the value of the array for the index k
args[k] = new int[]{6815, 11524};
}

NB: If you don't know the size of your array, consider using a List instead. The code will then be something like that:

List<int[]> args = new ArrayList<>();
...
args.add(new int[]{6815, 11524});

How to create Dynamic Two Dimensional Array [JAVA]

It may be more appropriate to use a Map<Double, List<Double>>. Having the value of the Map as a List<Double> will allow you to expand the list as opposed to an array which has a fixed size.

public static void main(String[] args) throws CloneNotSupportedException {
Map<Double, List<Double>> myMap = create(1, 3);
}

public static Map<Double, List<Double>> create(double row, double column) {
Map<Double, List<Double>> doubleMap = new HashMap<Double, List<Double>>();

for (double x = 0; x < row; x++) {
for (double y = 0; y < column; y++) {
doubleMap.put(x, new ArrayList<Double>());
}
}
return doubleMap;
}

How to create a dynamic 2D Array in java

You need to re-initialize Arr1 for every new row. Something like this:

    int rows = 3, columns = 4;
ArrayList<Integer> Arr1;
ArrayList<ArrayList<Integer>> Arr2 = new ArrayList<>();
for (int i = 0; i < rows; i++) {
Arr1 = new ArrayList<>();
for (int j = 0; j < columns; j++) {
Arr1.add(j);
}
Arr2.add(Arr1);
}
System.out.println(Arr2);

Which should out:

[[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]

Filling multidimensional Array Dynamic

I agree with the comments, use an ArrayList or List Interface: List<List<Double>> doublesList = new ArrayList<>(); This can grow dynamically. Here are a couple of examples:

// A List of Lists. Both can grow dynamically.
List<List<Double>> doublesList = new ArrayList<>();
List<Double> dList = Arrays.asList(3.17, 26.348);
doublesList.add(dList);

dList = Arrays.asList(3.65, 24.198, 44.657);
doublesList.add(dList);

// and so on...

//Display the list contents
for (List<Double> dl : doublesList) {
System.out.println(dl);
}

Or you can do something like this:

// A List of double[] arrays. The list can grow Dynamically but
// the double[] arrays within each List element are fixed length.
List<double[]> dpList = new ArrayList<>();
double[] dbl = {3.17, 26.348};
dpList.add(dbl);

dbl = new double[] {3.65, 24.198, 44.657};
dpList.add(dbl);

System.out.println();

//Display the list contents
for (double[] dl : dpList) {
System.out.println(Arrays.toString(dl));
}


Related Topics



Leave a reply



Submit