how to delete last array in java

how to delete last array in java

To delete the last element of an array in Java, you can use one of the following approaches:

  1. Create a new array without the last element:
ref‮al:ot re‬utturi.com
int[] array = {1, 2, 3, 4, 5};
int[] newArray = new int[array.length - 1];

System.arraycopy(array, 0, newArray, 0, array.length - 1);

This will create a new array newArray that is one element shorter than the original array and contains all the elements of the original array except for the last element.

  1. Use the System.arraycopy method to copy the elements of the array except for the last element:
int[] array = {1, 2, 3, 4, 5};

System.arraycopy(array, 0, array, 0, array.length - 1);
array[array.length - 1] = 0;  // set the last element to its default value

This will copy the elements of the array except for the last element, and set the last element to its default value (0 for integers).

Note that these approaches only modify the array in place, and do not delete the last element permanently. If you need to delete the element permanently, you can use a dynamic data structure like an ArrayList instead of an array.

The ArrayList class has a remove method that removes the element at the specified index, and adjusts the size of the list accordingly.

For example:

List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
Created Time:2017-11-01 20:42:49  Author:lautturi