jacquessl
jacquessl

Reputation: 1

Is it possible to create two dimensional array and declare length of each row later?

Is there any way to declare length of each row later?

public static void main(String[] args){
    int[][] arrr = new int[3][];
    int[] arrr[0] = new int[3];
    int[] arrr[1] = new int[4];
    int[] arrr[2] = new int[5];
}

I know in this example it looks unnecessary, but I wanted to show it as simple as possible.

Upvotes: 0

Views: 113

Answers (1)

WheelerShigley
WheelerShigley

Reputation: 51

"In Java, ArrayList is a resizable implementation." For arrays of variable size (modifiable at runtime), import and use the ArrayList object.

Here's an example:

import java.util.ArrayList;

class Main {
  public static void main(String[] args){

    //creating an ArrayList
    ArrayList<Integer> grades = new ArrayList<>();
    
    //Adding an element to ArrayList
    grades.add(99); //you'd want to use a Scanner or similar to input grades like this
    
    //Accessing an element of the ArrayList
    System.out.println( grades.get(0) ); //grades[0] equivalent

  }
}

This can also be done for 2D dynamic arrays:

import java.util.ArrayList;

class Main {
  public static void main(String[] args){

    //creating an ArrayList of ArrayLists of ints
    ArrayList< ArrayList<Integer> > grades = new ArrayList<>();
    
    //Adding an element to the list
    grades.at(0).at(0).add(99); //grades[0][0] where the second 0 is dynamically added
    
    //Accessing an element of the list
    System.out.println( grades.at(0).get(0) ); //grades[0][0] equivalent

  }
}

Documentation: https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html

Upvotes: 1

Related Questions