Tuesday, January 31, 2012

Tuples in Java

I came across the concept of tuples in C# which is quite interesting and useful. A tuple is a data structure that has a specific number and sequence of elements.  C# introduced this feature since .NET 3.5. It supports upto 8 generic objects. Unfortunately Java haven't got one yet.


In my current project there was a need for a similar Data-structure, where I had to pass back a large amount of data of a particular object. But I was interested only in just two properties of that object. I could have created a proxy class, but that would have ben a sort of over engineering (Which I don't want to do). At that time I thought of a simple attempt to write a Tuple. I wrote one and it's really reusable and clean. You can find the  the code snippet below.

public abstract class Tuple<T1, T2, T3, T4>{


    protected T1 t1;
    protected T2 t2;
    protected T3 t3;
    protected T4 t4;
    
    public static    < T1, T2> Tuple <T1, T2, ?, ?> create(T1 aT1, T2 aT2){
        return new MultipleTuple(aT1, aT2);
    }
    
    public  T1 getFirstItem(){
        return t1;
    }
    
    public T2 getSecondItem(){
        return t2;
    }
    
    public T3 getThirdItem(){
        return t3;
    }
    
    public T4 getFourthItem(){
        return t4;
    }

}

A MultiTuple


final class MultipleTuple<T1, T2> extends Tuple {
    
     MultipleTuple(T1 aT1, T2 aT2) {
        t1 = aT1;
        t2 = aT2;
    }
}


Example


String employee = "Diego Maradona";
double renumeration = 56.5;
        
Tuple  tuple = Tuple.create(employee, renumeration);


System.out.println(tuple.getFirstItem());
System.out.println(tuple.getSecondItem());




You can extend as many classes you want to create. You might need to restrict the visiblilty and make them final so that it's secure. Or you could even extend the MultipleTuple(Hoping it's no longer final) class for the next tuples. Make sure the create method is overloaded with the right parameters.




Happy Hacking.

No comments: