0

I'm working on the following problem where I have to create said method:

int[] runLength(int[] a) that takes an array that consists of a series of element values followed by the lengths of the run of those elements, listed in alternating locations. This method creates and returns a new array that contains these elements, each element repeated the number of times given by its run length. For example, when called with the array {3, 8, 1, -7, 0, 42, 4, -3} (read this out loud as “three eights, one minus seven, zero forty-twos, and four minus threes”), your method would create and return the array {8, 8, 8, -7, -3, -3, -3, -3}. Again, make sure that the array returned by your method has the exact right length.

public int[] runLength(int[] a) {

    int[] answer;

    for(int i = 0; i <= answer.length; i++) {
        if(i % 2 != 0) {
            for(int j = 0; j < i; j++) {
                // answer.push(i+1); is what I would do in Javascript
            }
        }
    }

}

I actually wrote this program in javascript first because i'm more familiar with it then translated into Java after (still sure I have a few errors with the for loop maybe. I'm actually steadily learning Java at the moment but realized that obviously Java has something different then the push() method when adding new values into an array. How exactly would I do this in Java then?

Hollow
  • 19
  • 4
  • 1
    This has already answered... https://stackoverflow.com/questions/2843366/how-to-add-new-elements-to-an-array –  Nov 02 '17 at 02:05

2 Answers2

0

Arrays (using []) are fixed size.

If you want to add things to an array, you need an ArrayList<T> instead.

Note that you can't add things to an array while iterating over the array, doing so will cause a ConcurrentModificationException to be thrown, crashing your program.

0

In java arrays are set a fixed size when you initialize them. The only way to 'change' the size of an array is make a new one and copy all the old values over. Fortunately Java has class called ArrayList that has the functionality you are looking for.

luckydog32
  • 909
  • 6
  • 13