Java Tuple Without Creating Multiple Type Parameters

陌路散爱 提交于 2019-12-12 01:46:39

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!