user3517375 user3517375 - 3 months ago 10x
Java Question

Store values from pyramid in jagged array

Here's my code:

ArrayList<ArrayList<Integer>> nums = new ArrayList<>();
int index = 0;
for(int i = 0; i < 15; i++){
nums.add(new ArrayList<Integer>());
int j = 0;
while(!(j > i)){
String s = "" + pyramid.charAt(index) + pyramid.charAt(index + 1);
int c = Integer.parseInt(s);

'Pyramid' is a string that contains a fifteen-row pyramid of numbers (top row has one number, next row has two numbers, etc.). Doing it this way, I get a jagged ArrayList.

My question is how do I accomplish this as an array? The only way I can think to get all of the numbers in their own array is to make an 2D array that is 15 arrays long with 15 spots in each array. Bit of a waste since I won't be using every index of every array (I only use every index with the last one). Any ideas?


If you really want to initialize a 2D jagged array you could do something like this:

 public static void main( String [] args){
   int [][] jaggedArray = new int [15][];
   for (int i=0; i<15; i++){
     jaggedArray[i] = new int[i+1];

However, in the question it looks like you're checking at runtime if the characters in the string are numbers and adding them dynamically. The problem with ArrayLists vs Arrays is that the former lets you change the size dynamically whereas the latter doesn't. So you either have to:

  • Know the static size ahead of time and intialize it the way above
  • Go through the string and determine the static size as others have said and then initialize it
  • Otherwise, you need to use a data structure that allows for dynamic resizing

Also, I'm not sure of the application, but if you're guaranteed that this thing won't be bigger than 15x15, I wouldn't worry too much about the tiny bit of over-allocation.