Home > other >  Filling multidimensional Array Dynamic
Filling multidimensional Array Dynamic

Time:04-06

i would like to create an Array with an structure like that

double[][] x1 = {{3.17, 26.348}, {3.65, 24.198}, {3.28, 25.085}, {3.37, 22.461},
        {2.57, 23.740}, {3.60, 24.786}, {3.50, 23.374}, {2.98, 23.725},
        {2.54, 23.227}, {3.41, 26.920}};

My Problem is that i dont know how big the array is going to be (how much value pairs). so i need it to be filled dynamic. I want to create the array out of two array lists in wich i stored the values

Something like this but dyamic for different sizes

 double[][] xtest = { {  ACDregList.get(0),  ALregList.get(0) },
            { ACDregList.get(1),  ALregList.get(1) },
            {  ACDregList.get(2),  ALregList.get(2) },
            {  ACDregList.get(3), ALregList.get(3) },
            {  ACDregList.get(4),  ALregList.get(4) },
            {  ACDregList.get(5),  ALregList.get(5) },
            {  ACDregList.get(6),  ALregList.get(6) },
            {  ACDregList.get(7),  ALregList.get(7) },
            {  ACDregList.get(8),  ALregList.get(8) },
            {  ACDregList.get(9),  ALregList.get(9) }};

Maybe some of you could help me out.

Thank you !

i already tried using two for loops but it did not fill the array the way i was expect

CodePudding user response:

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));
}

CodePudding user response:

In Java, array sized are fixed, you may be use Map instead of 2D array if key values are unique or use ArrayList

  • Related