不创建多个类型参数的 Java 元组 [英] Java Tuple Without Creating Multiple Type Parameters

查看:26
本文介绍了不创建多个类型参数的 Java 元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以在 Java 中创建 Tuple,无需创建多个类?

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];
    }
}

除非使用 this,所有对象在从元组中取出后都必须转换为正确的子类,使其类似于 ArrayList,但更少功能.

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.

有没有办法只创建一个单一的类,并有多个 Type Parameters 没有定义所有的参数(就像在第一个例子中一样),使用这样的东西?

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...>{

}

推荐答案

不.如果你想要类型安全,你必须像你在第一个代码片段中展示的那样创建它们.有一些库可以为您执行此操作,jOOL,例如.

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.

这篇关于不创建多个类型参数的 Java 元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆