问题
Is there any way to create a Tuple in Java, without having to create multiple classes?
For example, it is possible to make a different class for every different type of Tuple, each with a different number of Type Parameters:
public class SingleTuple<T>{}
public class DoubleTuple<T1, T2>{}
public class TripleTuple<T1, T2, T3>{}
public class QuadraTuple<T1, T2, T3, T4>{}
public class PentaTuple<T1, T2, T3, T4, T5>{}
And it's also possible to create a Tuple object without any Type Parameters by just doing this:
public class Tuple{
private Object[] objects;
public Tuple(Object... objects){
this.objects = objects;
}
public Object get(int index){
return this.objects[index];
}
}
Except if this is used, all of the objects would have to be casted to their correct subclass once they are taken out of the Tuple, making it like an ArrayList<Object>
, but with less features.
Is there any way to just create one singular class, and have multiple Type Parameters without defining all of them (like in the first example), using something like this?
public class Tuple<T...>{
}
回答1:
Nope. If you want type safety, you'll have to create them like you've presented in your first code snippet. There are libraries that do this for you, jOOL, for example.
回答2:
There is a hideous workaround.
All you need is a class Pair<A, B>
. Then, instead of a QuadraTuple<T1, T2, T3, T4>
you could have a Pair<T1, Pair<T2, Pair<T3, T4>>>
.
To get the T3
out of it, you'd have to write T3 t3 = quadraTuple.second().second().first();
. It's type-safe and extends to any number of parameters.
Never do this.
来源:https://stackoverflow.com/questions/29000231/java-tuple-without-creating-multiple-type-parameters