Java – how to add elements to the end of an array?
•
Java
I want to know how to add or append a new element to the end of the array Is there a simple way to add elements at the end? I know how to use StringBuffer, but I don't know how to use it to add elements to an array No ArrayList or list, I prefer it I wonder if StringBuffer can handle integers
Solution
You cannot add elements to an array because arrays in Java are fixed length However, you can use arrays Copyof (array, size) build a new array from an existing array:
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 still recommend abandoning arrays and using list
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码