remove delete an element from an array java
다른 배열 사용, Java 8 스트림 사용, ArrayList 사용과 같이 Java의 배열에서 요소를 삭제하거나 제거하는 다양한 방법을 알아보십시오.
Java 배열은 요소를 제거하기위한 직접 제거 메소드를 제공하지 않습니다. 사실, 우리는 이미 Java의 배열이 정적이므로 인스턴스화되면 배열의 크기를 변경할 수 없다고 이미 논의했습니다. 따라서 요소를 삭제하고 배열 크기를 줄일 수 없습니다.
따라서 배열에서 요소를 삭제하거나 제거하려면 일반적으로 해결 방법 인 다른 방법을 사용해야합니다.
=> 초보자를위한 전체 Java 교육 자습서 시리즈보기
학습 내용 :
Java의 배열에서 요소 제거 / 삭제
이 튜토리얼에서는 배열에서 요소를 삭제하는 다양한 방법에 대해 설명합니다.
다음이 포함됩니다.
- 다른 어레이 사용
- 자바 8 스트림 사용
- ArrayList 사용
- System.arraycopy () 사용
다른 어레이 사용
이것은 배열 요소를 삭제하는 전통적이고 다소 비효율적 인 방법입니다. 여기서 우리는 원래 배열에 대해 크기가 1보다 작은 새 배열을 정의합니다. 그런 다음 원래 배열의 요소를 새 배열로 복사합니다. 그러나이 복사를 수행하는 동안 지정된 인덱스의 요소를 건너 뜁니다.
이렇게하면 삭제할 요소를 제외한 모든 요소를 새 배열에 복사하여 요소가 삭제되었음을 나타냅니다.
이 작업을 아래와 같이 그림으로 표현할 수 있습니다.
이 메서드를 Java 프로그램에서 구현해 보겠습니다.
import java.util.Arrays; class Main { public static void main(String[] args) { // define original array int[] tensArray = { 10,20,30,40,50,60}; // Print the original array System.out.println('Original Array: ' + Arrays.toString(tensArray)); // the index at which the element in the array is to be removed int rm_index = 2; // display index System.out.println('Element to be removed at index: ' + rm_index); // if array is empty or index is out of bounds, removal is not possible if (tensArray == null || rm_index<0 || rm_index>= tensArray.length) { System.out.println('No removal operation can be performed!!'); } // Create a proxy array of size one less than original array int[] proxyArray = new int[tensArray.length - 1]; // copy all the elements in the original to proxy array except the one at index for (int i = 0, k = 0; i 산출:
월드 오브 워크래프트 전용 서버

자바 8 스트림 사용
스트림은 버전 8부터 Java에 새로 추가되었습니다. Java8 스트림을 사용하여 배열에서 요소를 삭제할 수 있습니다. 이를 위해 먼저 배열이 스트림으로 변환됩니다. 그런 다음 지정된 인덱스의 요소가 스트림의 필터 메서드를 사용하여 삭제됩니다.
요소가 삭제되면‘map’및‘toArray’메소드를 사용하여 스트림이 다시 배열로 변환됩니다.
스트림을 사용하여 배열에서 요소를 제거하는 구현은 다음과 같습니다.
import java.util.Arrays; import java.util.stream.IntStream; class Main { // Function to remove the element public static int[] removeArrayElement(int[] oddArray, int index) { //array is empty or index is beyond array bounds if (oddArray == null || index <0 || index>= oddArray.length) { return oddArray; } // delete the element at specified index and return the array return IntStream.range(0, oddArray.length) .filter(i -> i != index) .map(i ->oddArray[i]).toArray(); } public static void main(String[] args) { int[] oddArray = { 1, 3,5,7,9,11}; // define array of odd numbers System.out.println('Original Array: ' + Arrays.toString(oddArray)); // Print the resultant array int index = 2; // index at which element is to be removed System.out.println('Element to be removed at index: ' + index); // display index // function call removeArrayElement oddArray = removeArrayElement(oddArray, index); // Print the resultant array System.out.println('Array after deleting element: ' + Arrays.toString(oddArray)); } }
산출:

ArrayList 사용
이 작업을 수행하기 위해 ArrayList를 사용할 수 있습니다. 배열에서 요소를 제거하려면 먼저 배열을 ArrayList로 변환 한 다음 ArrayList의 'remove'메서드를 사용하여 특정 인덱스에서 요소를 제거합니다.
일단 제거되면 ArrayList를 다시 배열로 변환합니다.
다음 구현은 ArrayList를 사용하여 배열에서 요소를 제거하는 방법을 보여줍니다.
import java.util.*; import java.util.stream.*; class Main { public static int[] remove_Element(int[] myArray, int index) { if (myArray == null || index <0 || index>= myArray.length) { System.out.println('non-existing index'); return myArray; } //array to arrayList List arrayList = IntStream.of(myArray) .boxed().collect(Collectors.toList()); // Remove the specified element arrayList.remove(index); // return the resultant array returnarrayList.stream().mapToInt(Integer::intValue).toArray(); } public static void main(String[] args) { int[] myArray = { 11,22,33,44,55,66,77,88,99,111 }; System.out.println('Original Array: ' + Arrays.toString(myArray)); int index = 10; System.out.println('Index at which element is to be deleted: ' + index); myArray = remove_Element(myArray, index); System.out.println('Resultant Array: ' + Arrays.toString(myArray) + '
'); index = 2; System.out.println('Index at which element is to be deleted: ' + index); myArray = remove_Element(myArray, index); System.out.println('Resultant Array: ' + Arrays.toString(myArray)); } }
산출:

위 프로그램은 두 가지 조건에 대한 출력을 생성합니다. 첫째, 존재하지 않는 인덱스 (10)가 전달됩니다. 즉, 현재 배열 크기를 초과합니다. 프로그램은 적절한 메시지를 표시하고 요소를 삭제하지 않습니다.
두 번째 경우에는 index = 2가 전달됩니다. 이번에는 위치 2의 요소가 삭제되고 결과 배열이 전달됩니다.
System.arraycopy () 사용
이 방법은 원래 배열의 요소를 새 배열로 복사하는 데 'arrayCopy'방법을 사용한다는 점을 제외하면 첫 번째 방법과 유사합니다.
먼저 원래 배열의 요소를 0에서 새 배열의 인덱스로 복사합니다. 다음으로 index + 1에서 length까지 요소를 새 배열에 복사합니다. 따라서 복사하는 동안 지정된 인덱스의 요소를 건너 뛰고 새 배열을 생성합니다.
이 새 배열은 지정된 인덱스에서 요소를 삭제 한 후 얻은 결과 배열을 나타냅니다.
import java.util.Arrays; class Main { public static void main(String[] args) { // define the array of integers int[] intArray = { 10,20,30,40,50 }; // display the original array System.out.println('Original Array: ' + Arrays.toString(intArray)); // index at which the element is to be deleted int index = 2; // the index System.out.println('Element to be deleted at index: ' + index); // check if the array is empty or index is out of bounds if (intArray == null || index <0 || index>= intArray.length) { System.out.println('No removal operation can be performed!!'); } // create an array to hold elements after deletion int[] copyArray = new int[intArray.length - 1]; // copy elements from original array from beginning till index into copyArray System.arraycopy(intArray, 0, copyArray, 0, index); // copy elements from original array from index+1 till end into copyArray System.arraycopy(intArray, index + 1, copyArray, index, intArray.length - index - 1); // display the copied array after deletion System.out.println('Array after deleting an element: ' + Arrays.toString(copyArray)); } }
산출:

자주 묻는 질문
Q # 1) 배열에서 하나의 요소를 제거하는 방법은 무엇입니까?
대답: Java는 배열에서 요소를 제거하는 직접적인 방법을 제공하지 않습니다. 그러나 요소가 삭제 될 인덱스가 주어지면 ArrayList를 사용하여 지정된 인덱스에서 요소를 제거 할 수 있습니다.
이를 위해 먼저 배열을 ArrayList로 변환하고 remove 메서드를 사용하여 요소를 제거합니다. 완료되면 ArrayList를 다시 배열로 변환합니다. 이 목적으로 사용할 수있는 몇 가지 다른 해결 방법도 있습니다.
Q # 2) ArrayList 제거는 무엇을합니까?
대답: ArrayList remove 메서드는 인수로 제공된 지정된 인덱스에서 ArrayList의 요소를 제거합니다.
기본 게이트웨이를 사용할 수 없음 Windows 7
Q # 3) Java의 어레이에서 중복을 어떻게 제거합니까?
대답: 배열에서 중복 된 요소는 요소를 하나씩 계산하고 임시 배열에 고유 한 요소 만 넣는 임시 배열을 사용하여 제거 할 수 있습니다. 중복을 제거하려면 배열을 정렬해야합니다.
Q # 4) 필터가 새 어레이를 반환합니까?
대답: 예. 필터는 원래 배열에 영향을주지 않고 새 배열을 반환합니다.
Q # 5) R은 어떻게 Java로 작업을 하시겠습니까?
대답: Java에서 ArrayList의 remove 메소드는 지정된 인덱스에서 요소를 제거합니다. 연결 목록에서도 remove 메서드는 주어진 위치에서 노드를 제거합니다.
결론
이 튜토리얼에서는 주어진 인덱스의 배열에서 요소를 제거 할 수있는 다양한 방법이나 해결 방법을 살펴 보았습니다.
이후 주제에서는 Java의 배열에서 수행되는 몇 가지 작업에 대해 설명합니다.
=> 여기에서 집중 Java 교육 가이드를 확인하십시오.
추천 도서