#How to delete elements from an array in JAVA?
Java arrays have a fixed length, so elements in the array cannot be deleted directly. (Recommended tutorial: java tutorial)
Delete the elements of the original array by creating a new array and assigning the retained elements in the original array to the new array. In the same way, elements can be added to an array.
import java.util.Arrays; public class ArrayTest1 { public static void main(String[] args) { int[] array1 = new int[] {4, 5, 6, 7}; int num = 2; int[] newArray = new int[array1.length-1]; for(int i=0;i<newArray.length; i++) { // 判断元素是否越界 if (num < 0 || num >= array1.length) { throw new RuntimeException("元素越界... "); } // if(i<num) { newArray[i] = array1[i]; } else { newArray[i] = array1[i+1]; } } // 打印输出数组内容 System.out.println(Arrays.toString(array1)); array1 = newArray; System.out.println(Arrays.toString(array1)); } }
The above is the detailed content of How to delete elements from an array in JAVA?. For more information, please follow other related articles on the PHP Chinese website!