0

What I trying to do is creating an empty array such as

char[] array = {};

then I have a method called append

static void append(char array[], char x) {
  array = Arrays.copyOf(array, array.length + 1);
  array[array.length - 1] = x;
}

for example, I try to append x into the empty array and it keeps throwing Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0

Gregor Koukkoullis
  • 2,255
  • 1
  • 21
  • 31
  • 3
    You'd have to create a method that returns a new array. If you want an array that grows, use a collection (List, Set). If you're worried about performance, don't. I had thousands of arrays being created, populated, read from, written to, and all of that in 60 fps with no hiccups. –  Mar 06 '21 at 22:57
  • Note that [StringBuilder](https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/lang/StringBuilder.html) does exactly what you have implemented in your code. – VGR Mar 07 '21 at 03:59

1 Answers1

0

Your append(char[], char) method actually works. If you just run this example you will see there is no exception.

import java.util.*;
public class Test {

     public static void main(String[] args){
        char[] array = {};
        append(array, 'b');
     }
     
     
     static void append(char[] array, char x) {
       array = Arrays.copyOf(array, array.length + 1);
       array[array.length - 1] = x;
     }
}

So your error must be somewhere else. Most likely your append method should return the newly generated array:

import java.util.*;
public class Test {

     public static void main(String[] args){
        char[] array = {};
        array = append(array, 'b');
        array = append(array, 'c');
     }
     
     static char[] append(char[] array, char x) {
       array = Arrays.copyOf(array, array.length + 1);
       array[array.length - 1] = x;
       return array;
     }
}
Gregor Koukkoullis
  • 2,255
  • 1
  • 21
  • 31