No Java 5 – No Varargs!
The release of Java version 5 has provided us with some interesting and useful new ways to do things that would usually require a lot of effort, for example the new for-each loop and varargs.Varargs allows you to send a variable amount of arguments to a method. This is very useful when you would like to create a utility method to perform actions on objects or lists. There are many different ways in which to do this. The easiest would be to send the method a list of the objects and then loop through the list.
public void init() {
// assign the objects
List list = new ArrayList();
list.add(obj1);
list.add(obj2);
list.add(obj3);
doSomething(list);
}
public void doSomething(List list) {
for (int i = 0; i < list.size(); i++) {
// do something
}
}
This method involves creating a new list, adding the object to the list, and then sending the list across to the method which then retrieves the objects from the list. In Java 5 this can be done with varargs and the new for each loop as follows:
public void init() {
// assign the objects
doSomething(obj1, obj2, obj3);
}
public void doSomething(Object … obj) {
for (Object ob: obj) {
// do something
}
}
As you can see, the above method is much more simplified than the previous one. I have become used to this new method and the other new stuff in Java 5. Then I was asked to develop a demo in GWT (Google Web Toolkit). First-off I must say that I am very impressed by the GWT framework and what they are trying to achieve and the ways in which this makes developing web-based applications easier by allowing you to code it all in Java (personally I hate debugging JavaScript). There is one thing, you are only allowed to use Java syntax up to version 1.4. Great, there goes all the lovely new features of Java 5.
There is another way to pass a variable amount of arguments to a method by just using Java 1.4 syntax. That is by passing an array of objects. Take a look at the following example:
public void init() {
// assign the objects
doSomething(new Object[] {obj1, obj2, obj3});
}
public void doSomething(Object[] obj) {
for (int i = 0; i < obj.length; i++) {
// do something
}
}
This provides the same way of doing it without using varargs. As varargs is basically an array which is being passed to the method as in this last example.
Let’s hope the Java 5 features will be implemented in GWT soon. But until then, this is how I will be implementing my own varargs.