
Collection::remove 메소드와 removeAll() 메소드는 모두 Collection에서 특정 객체를 제거하는 목적으로 사용됩니다.
remove() 메소드는 Collection에서 특정 객체를 제거할 때 사용됩니다. 이 메소드는 객체의 동일성을 체크하여 객체가 동일한지 확인합니다. 동일성은 객체의 주소 값을 비교하는 것입니다. 따라서 객체의 내용만 같아도 제거가 되지 않습니다.
removeAll() 메소드는 Collection에서 모든 객체를 제거할 때 사용됩니다. 이 메소드는 Collection에서 모든 객체를 제거합니다.
removeIf() 메소드는 Collection에서 특정 조건에 해당하는 객체를 제거할 때 사용됩니다. 이 메소드는 Predicate를 사용하여 객체를 제거합니다. Predicate는 객체의 내용을 체크할 수 있기 때문에 remove() 메소드보다 유용합니다.
예를 들어, Collection에 저장된 Student 객체를 제거할 때, remove() 메소드는 Student 객체의 동일성을 체크하여 객체가 동일한지 확인합니다. 하지만 removeIf() 메소드는 Predicate를 사용하여 Student 객체의 내용을 체크할 수 있기 때문에 remove() 메소드보다 유용합니다.
예시:
#hostingforum.kr
java
List students = new ArrayList<>();
students.add(new Student("John", 20));
students.add(new Student("Jane", 22));
students.add(new Student("John", 20));
// remove() 메소드
students.remove(new Student("John", 20));
System.out.println(students); // [Jane, John@15db9742, John@15db9742]
// removeIf() 메소드
students.removeIf(student -> student.getName().equals("John"));
System.out.println(students); // [Jane]
결론적으로, remove() 메소드는 객체의 동일성을 체크하여 객체가 동일한지 확인합니다. 하지만 removeIf() 메소드는 Predicate를 사용하여 객체의 내용을 체크할 수 있기 때문에 remove() 메소드보다 유용합니다.
2025-07-14 22:37