Java Reference
In-Depth Information
To put your knowledge of default methods to use, have a go at Quiz 9.1 .
Quiz 9.1: removeIf
For this quiz, pretend you're one of the masters of the Java language and API. You've received
many requests for a removeIf method to use on ArrayList, TreeSet, LinkedList, and all other
collections. The removeIf method should remove all elements from a collection that match a
given predicate. Your task in this quiz is to figure out the best way to enhance the Collections
API with this new method.
Answer:
What's the most disruptive way to enhance the Collections API? You could copy and paste the
implementation of removeIf in each concrete class of the Collections API, but that would be a
crime to the Java community. What else can you do? Well, all of the Collection classes
implement an interface called java.util.Collection. Great; can you add a method there? Yes; you
just learned that default methods are a way to add implementations inside an interface in a
source-compatible way. And all classes implementing Collection (including classes from your
users that aren't part of the Collections API) will be able to use the implementation of removeIf.
The code solution for removeIf is as follows (which is roughly the implementation in the official
Java 8 Collections API). It's a default method inside the Collection interface:
default boolean removeIf(Predicate<? super E> filter) {
boolean removed = false;
Iterator<E> each = iterator();
while(each.hasNext()) {
if(filter.test(each.next())) {
each.remove();
removed = true;
}
}
return removed;
}
Search WWH ::




Custom Search