Thursday, August 6, 2009

Multiple Return Values in Java

How can we have multiple return values in Java? We cannot formally have it, since each method can only have no return value (void) or single return value (int, long, Object, String, etc.)

One of the solution to emulate it is to create a class that contains two fields, one for each return value. But that will make you tired because you need to create it every time you need it (not including the time used to think what the class name should be).

In my case, I solved this problem by using a Pointer class. It works similar to C in which you can have multiple return values by passing a pointer to a value that will be modified to the function arguments like: size = fread(pbuf, size, count, pfile);

The pointer class is as follows:

public class Pointer<T> {
  public T value;
  public static <T> Pointer<T> create() {
    return new Pointer<T>();

Let's say you have a method that needs to return two values: result and error code. The method for our example will be:

byte[] downloadFile(String url, Pointer<Integer> errorCode) {
  ...(really download)...
  if (errorCode != null) {
    errorCode.value = 200; // example only

To use the method, we first create the pointer to store the error code as follows:

Pointer<Integer> errorCode = Pointer.create();
byte[] file = downloadFile("", errorCode);
System.out.printf("File downloaded (%d bytes) with error code %d", file.length, errorCode.value);

The reason of the create() is to eliminate repeated typing of the type parameter:

Pointer<Integer> errorCode = new Pointer<Integer>();

No comments:

Post a Comment