Thursday 11 July 2013

A tuple implementation in Java

Here is a fairly simple implementation of tuples in Java. The purpose of tuples is to aggregate values of any type into a single object, which is strongly typed. This implementation follows the way .NET implements tuples. For other examples you could look in StackOverflow.com (example: here).

It begins with an interface for all tuple types:

package net.intrepidis.library.tuple;

public interface Tuple
{
 int size();
}

Here's a tuple of two items:



package net.intrepidis.library.tuple;

public class Tuple2<T1,T2> implements Tuple
{
 public final T1 item1;
 public final T2 item2;
 
 public Tuple2(
  final T1 item_1,
  final T2 item_2)
 {
  item1 = item_1;
  item2 = item_2;
 }

 @Override
 public int size()
 {
  return 2;
 }
}

Here's a tuple of three items:




package net.intrepidis.library.tuple;

public class Tuple3<T1,T2,T3> implements Tuple
{
 public final T1 item1;
 public final T2 item2;
 public final T3 item3;

 public Tuple3(
  final T1 item_1,
  final T2 item_2,
  final T3 item_3)
 {
  item1 = item_1;
  item2 = item_2;
  item3 = item_3;
 }

 @Override
 public int size()
 {
  return 3;
 }
}


This code is completely free to use by anybody. It is held under the Do What You Want To Public License: http://tinyurl.com/DWYWTPL

No comments:

Post a Comment