Java Generics

This is an example of how you might implement some functional programming in Java. I was reading about scala on this page:, where I stumbled into this code.

It ocurred to me that this is a great little code snippet for learning about generics. Java doesn't have an Array class, but let's pretend it did. The idea here is that you want to create a 'foreach' method in the Array class that that takes a Callback as an argument. The foreach method loops through each item in the array and passes the item into the 'operate' method of the callback. Since you can't pass functions as params in Java, the best we can do is pass an instance of Callback into our foreach method and invoke operate().

Here are the classes:


public interface Callback<T> {
public void operate(T element);

public class Array<T> {
public void foreach(Callback<T> callback){

// assume that this.elements holds the data for our Array
for(T e : this.elements) {



Now here's how you might use this code:


public class HelloWorld {

public static void main(Array<String> args){

final StringBuilder sb = new StringBuilder();

args.foreach(new Callback<String>(){
public void operate(String element){






Add a Comment...



There's certainly a great deal to know about this issue. I love all the points you made. maglietta juventus - 4/26/2017

Thanks for another great article. Where else could anybody get that kind of information in such a perfect method of writing? I have a presentation next week, and I'm on the search for such info. fotbollströjor - 4/26/2017

LucasStei Liverpool JodiDault LavondaHa Olympique Lyonnais VirgilioE CornellKw Ukraina KelleHard DorothyWa Juventuss ChandraCa BobbyeRun Liverpool MoraVeneg DrewSorre Liverpool TomMosman RafaelSla BVB Borussia Dortmund ArethaKir BobbyeRun Liverpool MoraVeneg SantoNico Olympique Lyonnais JedMorey KarryMtn Real Madrid Evangelin - 3/07/2017