
FilterIterator의 accept 메서드는 Iterable의 요소가 FilterIterator의 필터링 조건을 만족하는지 확인하여 true 또는 false를 반환하는 메서드입니다.
accept 메서드는 Iterable의 요소를 필터링하는 데 사용되는 조건을 결정하는 데 사용되는 Predicate 인터페이스를 구현한 객체를 필드에 저장합니다. 이 Predicate 객체는 accept 메서드가 호출될 때마다 Iterable의 요소가 필터링 조건을 만족하는지 확인합니다.
예를 들어, 다음과 같이 Predicate 인터페이스를 구현한 객체를 생성할 수 있습니다.
#hostingforum.kr
java
public class OddNumberPredicate implements Predicate {
@Override
public boolean test(Integer number) {
return number % 2 != 0;
}
}
이 예제에서는 OddNumberPredicate 클래스가 Predicate 인터페이스를 구현하고, test 메서드가 OddNumberPredicate 객체가 필터링 조건을 만족하는지 확인하는 메서드입니다.
accept 메서드는 Predicate 객체를 필드에 저장하고, Iterable의 요소를 필터링하는 데 사용됩니다.
#hostingforum.kr
java
public class FilterIterator implements Iterator {
private Predicate predicate;
private Iterator iterator;
public FilterIterator(Iterator iterator, Predicate predicate) {
this.iterator = iterator;
this.predicate = predicate;
}
@Override
public boolean accept(Integer number) {
return predicate.test(number);
}
@Override
public boolean hasNext() {
while (iterator.hasNext()) {
if (accept(iterator.next())) {
return true;
}
}
return false;
}
@Override
public Integer next() {
if (hasNext()) {
return iterator.next();
} else {
throw new NoSuchElementException();
}
}
}
이 예제에서는 FilterIterator 클래스가 Predicate 인터페이스를 구현한 객체를 필드에 저장하고, accept 메서드를 호출하여 Iterable의 요소가 필터링 조건을 만족하는지 확인합니다. hasNext 메서드는 accept 메서드를 호출하여 Iterable의 요소가 필터링 조건을 만족하는지 확인하고, next 메서드는 hasNext 메서드가 true를 반환할 때까지 Iterator의 next 메서드를 호출하여 Iterable의 요소를 반환합니다.
accept 메서드는 Iterable의 요소를 필터링하는 데 사용되는 조건을 결정하는 데 사용되는 Predicate 인터페이스를 구현한 객체를 필드에 저장하고, accept 메서드를 호출하여 Iterable의 요소가 필터링 조건을 만족하는지 확인합니다.
2025-07-18 12:26