Reputation: 4803
let's say i have a list with some elements and i want to choose all those who do not satisfy a certain condition. i was thinking about something like this:
public void choose(Condition c) {
choose all elements that satisfy c.CheckCondition(elem)
}
however, i think it's highly unelegant and it forces to user to implement a Condition
object with
a certain function that will check if an element satisfies a condition.
if it was c++ i would send a pointer to a function as a parameter but its not possible in java.
I thought about using Comparable
object but it's no good since i have to implement it in my class instead of getting it from the user.
any other elegant ideas for this problem?
thanks!
Upvotes: 1
Views: 630
Reputation: 500663
I think what you propose is fairly elegant, especially when combined with generics and anonymous classes:
set.choose(new Condition<Elem>() {
boolean checkCondition(Elem elem) {
...
}
});
Upvotes: 0
Reputation: 6149
Not for now - Java 7 still does not have closures ("function pointers" in C). It may come in Java 8. In the meantime, we're stuck at writing our predicates as classes...
But you may be interested in the Guava library. It's developed by Google, and already provides classes to filter, map or transform the elements of a collection. http://code.google.com/p/guava-libraries/
Upvotes: 2