R.E.M. Web Development

Java Generics

This is an example of how you might implement some functional programming in Java. I was reading about scala on this page: http://www.codecommit.com/blog/scala/scala-for-java-refugees-part-1, 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) {
callback.operate(e);
}

}
}

 

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){
sb.append(element);
}
});

System.out.println(sb.toString());
}
}