Home > Java > JavaBase > body text

How to delete elements from an array in JAVA?

angryTom
Release: 2019-11-12 13:30:49
Original
7223 people have browsed it

How to delete elements from an array in JAVA?

#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));
	}
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template