Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create Dynamic Two Dimensional Array [JAVA]

I am new to java and I want to create a 2-dimensional array in which the rows are static but the columns are dynamic.

double [][] lastSecArray = new double [2][41];
int lastValue = -1;
public foo (){
   lastValue++;
   lastSecArray[0][lastValue] = st_ms;
   //more code here
}

The value of lastValue increases and when it reaches 41 my program gives me Array Index out of bound. Which is what I should expect.

How can I make the column of teh array dynamic so that no matter how large the value of lastValue increases it runs.

like image 283
Wearybands Avatar asked Feb 16 '23 14:02

Wearybands


2 Answers

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;
}
like image 73
Kevin Bowersox Avatar answered Feb 27 '23 13:02

Kevin Bowersox


Try to use

Map<String, ArrayList> lastSecArray = new HashMap<>();
    ArrayList value = new ArrayList();
    value.add(0);
    value.add(1);
    value.add(2);
    lastSecArray.put("0", value);

so you can operate with

lastSecArray.size()

or

lastSecArray.put(...)

or array in array

like image 29
Batyr Malik Avatar answered Feb 27 '23 13:02

Batyr Malik