How to add an element at the end of an array? How to add an element at the end of an array? arrays arrays

How to add an element at the end of an array?


You can not add an element to an array, since arrays, in Java, are fixed-length. However, you could build a new array from the existing one using Arrays.copyOf(array, size) :

public static void main(String[] args) {    int[] array = new int[] {1, 2, 3};    System.out.println(Arrays.toString(array));    array = Arrays.copyOf(array, array.length + 1); //create new array from old array and allocate one more element    array[array.length - 1] = 4;    System.out.println(Arrays.toString(array));}

I would still recommend to drop working with an array and use a List.


Arrays in Java have a fixed length that cannot be changed. So Java provides classes that allow you to maintain lists of variable length.

Generally, there is the List<T> interface, which represents a list of instances of the class T. The easiest and most widely used implementation is the ArrayList. Here is an example:

List<String> words = new ArrayList<String>();words.add("Hello");words.add("World");words.add("!");

List.add() simply appends an element to the list and you can get the size of a list using List.size().


The OP says, for unknown reasons, "I prefer it without an arraylist or list."

If the type you are referring to is a primitive (you mention integers, but you don't say if you mean int or Integer), then you can use one of the NIO Buffer classes like java.nio.IntBuffer. These act a lot like StringBuffer does - they act as buffers for a list of the primitive type (buffers exist for all the primitives but not for Objects), and you can wrap a buffer around an array and/or extract an array from a buffer.

Note that the javadocs say, "The capacity of a buffer is never negative and never changes." It's still just a wrapper around an array, but one that's nicer to work with. The only way to effectively expand a buffer is to allocate() a larger one and use put() to dump the old buffer into the new one.

If it's not a primitive, you should probably just use List, or come up with a compelling reason why you can't or won't, and maybe somebody will help you work around it.