To add an element to an array in Java, first convert the array to a
List
, then add the element to that List
, finally convert the List
back to an array.Here's how you do it:
String[] array = new String[] { "Hello" };
java.util.List<String> list = new java.util.ArrayList<>(java.util.Arrays.asList(array));
list.add("World");
String[] biggerArray = list.toArray(String[]::new);
// [Hello]
System.out.println(java.util.Arrays.toString(array));
// [Hello, World]
System.out.println(java.util.Arrays.toString(biggerArray));