How can an element append into an empty array in java? [duplicate]

171
March 07, 2021, at 10:00 PM
This question already has answers here:
Is Java “pass-by-reference” or “pass-by-value”? (85 answers)
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it? (27 answers)
Closed 19 hours ago.

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

Answer 1

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;
     }
}
Rent Charter Buses Company
READ ALSO
Can I obtain the parameters of the website using Brython?

Can I obtain the parameters of the website using Brython?

I am currently trying to use Brython for the website I am making, but I cannot get the data from the user for my program

40
When i refresh a VueJS page with opened modale i loose CSS style

When i refresh a VueJS page with opened modale i loose CSS style

I have a little problem, a little "classic" question, but I can't find an answer to this one

140
How to set timeout with abort controller and retry in ES7 async await function

How to set timeout with abort controller and retry in ES7 async await function

I am trying fetch request, if request takes time longer than specified timeout then I am aborting it using abort controller or if there is error in response like socket hangup then try to fetch it again recursivelyI want to repeat it i

150
How do I Select Objects inside an Array in Mongoose?

How do I Select Objects inside an Array in Mongoose?

Below is the Model of the database which I am using with mongoose and nodejs

164