java 元组_简单实现 Java 的 Tuple 元组数据类型

元组类型,即 Tuple 常在脚本语言中出现,例如 Scala 的 ("Unmi", "fantasia@sina.com", "blahbla")。元组可认为是象数组一样的容器,它的目的是让你方便构造和引用,例如 Pair 可认为是一个只能存两个元素的元组,像是个 Map; 真正的元组应该是可以任意多个元素的容器,绕来绕去,它还是数组,或列表,所以我们实现上还是要借助于数组或是列表。

先看 Scala 中什么是元组:

val tuple = ("Unmi", "fantasia@sina.com", "blahblah...")

println(tuple._1) //输出 Unmi

1

2

valtuple=("Unmi","fantasia@sina.com","blahblah...")

println(tuple._1)//输出 Unmi

Scala 中访问从 1 开始,用 ._1 方式来访问其中的元素。

参照于此,写出一个 Java 版本的 Tuple,为增长你的键盘的使用寿命,我们把方法名也缩短了,例如 make 缩写为 mk,引用元素的方法名为 _,仍然保持 Java 的习惯,索引从 0 开始:

package cc.unmi.utils;

/**

 * A simple java tuple

 * @author Unmi

 * @creation_date 2012/02/04

 */

public class Tuple<A> {

    public static <A> Tuple mk(A ... args){

        return new Tuple(args);

    }

    private A[] items;

    private Tuple(A[] items) {

        this.items = items;

    }

    public A _(int index){

        if(index < 0 || items == null || index > items.length-1){

            return null;

        }

        return items[index];

    }

    public static void main(String[] args) {

        Tuple<String> t = Tuple.mk("Unmi","fantasia@sina.come");

        System.out.println(t._(0)); //输出 Unmi

    }

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

packagecc.unmi.utils;

/**

 * A simple java tuple

 * @author Unmi

 * @creation_date 2012/02/04

 */

publicclassTuple<A>{

   publicstatic<A>Tuplemk(A...args){

      returnnewTuple(args);

   }

   privateA[]items;

   privateTuple(A[]items){

      this.items=items;

   }

   publicA_(intindex){

      if(index<0||items==null||index>items.length-1){

         returnnull;

      }

      returnitems[index];

   }

   publicstaticvoidmain(String[]args){

      Tuple<String>t=Tuple.mk("Unmi","fantasia@sina.come");

      System.out.println(t._(0));//输出 Unmi

   }

}

代码间加了一个 main 测试方法,上面的代码输出什么无需多说了。

这样就实现了 Tuple.mk()  后接任意多个参数来构造一个 Tuple 对象。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值