
Collection::remove 메소드는 컬렉션에서 특정 요소를 제거할 때 사용됩니다.
컬렉션에 중복된 요소가 있는 경우, remove 메소드는 첫 번째로 발견되는 요소를 제거합니다.
remove 메소드를 사용하면 컬렉션에서 해당 요소를 제거하고, 그 요소를 반환합니다.
그러나, 반환되는 요소는 컬렉션에서 제거된 요소가 아닐 수 있습니다. 컬렉션에서 제거된 요소가 반환되지 않을 수 있는 이유는 컬렉션에서 제거된 요소가 컬렉션 내에서 중복된 요소일 수 있기 때문입니다.
remove 메소드를 사용할 때, 컬렉션의 순서는 유지되지 않습니다. 컬렉션의 순서는 remove 메소드가 호출된 시점에 컬렉션의 순서를 유지하는지 여부에 따라 달라집니다.
ArrayList에 중복된 요소를 제거하는 방법은 다음과 같습니다.
#hostingforum.kr
java
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("apple");
list.add("orange");
System.out.println("원본 리스트 : " + list);
list.remove("apple");
System.out.println("중복된 요소 제거 후 리스트 : " + list);
}
}
이 예제에서, ArrayList에 중복된 요소인 "apple"가 제거됩니다.
중복된 요소가 제거된 후, ArrayList의 순서는 다음과 같습니다.
#hostingforum.kr
원본 리스트 : [apple, banana, apple, orange]
중복된 요소 제거 후 리스트 : [banana, apple, orange]
중복된 요소가 제거된 후, ArrayList의 순서는 유지되지 않습니다.
ArrayList의 순서는 remove 메소드가 호출된 시점에 ArrayList의 순서를 유지하는지 여부에 따라 달라집니다.
ArrayList의 순서를 유지하려면, ArrayList의 인덱스를 사용하여 요소를 제거해야 합니다.
#hostingforum.kr
java
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("apple");
list.add("orange");
System.out.println("원본 리스트 : " + list);
int index = list.indexOf("apple");
if (index != -1) {
list.remove(index);
}
System.out.println("중복된 요소 제거 후 리스트 : " + list);
}
}
이 예제에서, ArrayList의 인덱스를 사용하여 중복된 요소인 "apple"를 제거합니다.
중복된 요소가 제거된 후, ArrayList의 순서는 다음과 같습니다.
#hostingforum.kr
원본 리스트 : [apple, banana, apple, orange]
중복된 요소 제거 후 리스트 : [banana, orange]
중복된 요소가 제거된 후, ArrayList의 순서는 유지됩니다.
2025-07-27 02:24