ImmutablePair和ImmutableTriple的使用

场景

当我们调用某个方法,需要有超过一个值的返回时,我们通常会怎么做,比如现在需要调用方法返回姓名和年龄两个属性(假如姓名为张三,年龄为12)。

  • 方式一:使用Map,将Map中分别放入name为key,张三为value;age为key,12为value。
    • 缺点是需要定义key值,且书写语法比较繁琐。
    • 优点是定义明确。
  • 方式二:直接定义一个Person对象,定义name和age两个属性。
    • 缺点是比较繁琐,这个Person对象可能整个项目中只被使用这一次。
    • 优点是定义非常明确,不容易产生歧义。

新的方法

下面介绍一种新的方法,当我们方法调用返回值大于一个属性,且就仅有这一次调用,不存在复用和共用问题时,可以采用如下方式:

package objectDemo;

import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.ImmutableTriple;

public class Demo {

    public static void main(String[] args) {
        ImmutablePair<String, Integer> person = ImmutablePair.of("张三", 12);
        System.out.println(person);

        ImmutableTriple<String, Integer, String> personInfo = ImmutableTriple.of("李四", 20, "上海");
        System.out.println(personInfo);
    }
}

输出结果为:

(张三,12)
(李四,20,上海)
原文地址:https://www.cnblogs.com/silenceshining/p/15249408.html