java 中使用 pair或者 triple 来优雅解决多返回值

java 不允许返回多个value,暴力点解决, 直接return数组, 规范一点封装个对象。

在返回两个或者三个返回值时,这几个返回值关系又没有强相关。

为了酷炫+通用,使用开发好的 pair 或者trple

commons-lang3

引入 commons-lang3.

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>

    // 可变 pair
    MutablePair<String, Exception> pair = new MutablePair<>();
    pair.setLeft("11");
    pair.setRight(new RuntimeException());

    System.out.println(pair.left);

    // 不可变pair
    ImmutablePair<String, Exception> pair2 = new ImmutablePair<>("11", new Exception());
    System.out.println(pair2.left);

    //  可变triple
    MutableTriple<String, Integer, Exception> triple = new MutableTriple<>();
    triple.setLeft("left");
    triple.setMiddle(22);
    triple.setRight(new RuntimeException());
    System.out.println(triple.left);

hutool 好像只提供了pair

引入依赖

cn.hutool
hutool-all
5.8.11

    // hutool 提供的pair
    Pair p = new cn.hutool.core.lang.mutable.MutablePair("ste", new RuntimeException());
    System.out.println(p.getKey());

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值