What does the FindAll method have to do with anything?
Very concise definition for a nice generic method in .NET I found to be similarly short and sweet. In my research, the goal was to create a more efficient means of searching for values in an array/list that met specific criteria without having to loop through each value. What I found was the FindAll method proved to be faster both in performance and actual code implementation.
Just one line of code to use as FindAll utilizes a delegate function known as a Predicate that takes one argument and returns a true or false if the argument meets criteria specified within the predicate's implementation.
For a better look at delegates from a Java perspective, you can read "A Java Programmer Looks at C# Delegates" by Steven M. Lewis and Wilhelm Fitzpatrick.
For my simple implementation, I chose to go with a Predicate interface and anonymous inner classes to simulate the delegate functionality.
- 1
Create Predicate Interface.
- 2
Create FindAll Function.
In .NET, you can utilize shared (static) functions from the List/Array class or from an instance of an implementation of List; therefore, a findAll method could be added to a custom List implementation in Java, but the code I went with uses a utility class that I could store other functions relating to predicates.
Originally, I implemented only the findAll with array argument in signature as it allowed for use with both arrays and lists through one function, but given the ability to overload methods I added the second as it makes calls easier when searching lists as you can simply pass the List object without having to convert it to an array first.
- 3
Enjoy!
As mentioned earlier, the anonymous inner class within Java allows you to utilize methods from your main class similar to the delegate function in .NET. Looks a little more than one line, but hopefully you agree that this is not a lot of Java code for what you are getting.
I found the FindAll method very useful and I am hoping you will as well. In addition, having a Predicate concept in Java may come in handy for other projects as well.
Thanks for taking the time to read the above. If you have any questions on how the code works that is not explained well enough in the code comments, please post below and I will be happy to clarify.
Happy coding!
Best regards,
Kevin (aka MWVisa1)
by: mwvisa1 on 2009-10-11 at 12:38:19ID: 4123
Here is an official white paper from Sun, discussing usage of Reflection API to implement delegation in Java using the J++ methodology : hite/sideb ar.html
og/alexwin ston/archi ve/2005/04 / strongly_ types_1.ht ml
http://java.sun.com/docs/w
And this follow-up article goes into strongly typed delegates (it references above, so good to read in order linked here) :
http://weblogs.java.net/bl
Regards,
Kevin