【问题标题】:What is a Triple in Java?Java中的三元组是什么?
【发布时间】:2018-10-17 20:09:51
【问题描述】:

我遇到过如下代码:

public List<Triple<String, String, Instant>> methodName() {
    // Do something
}

Triple是什么,应该怎么用?

【问题讨论】:

  • 它从哪个包导入Triple?只需找到相关的 Javadoc。

标签: java object store


【解决方案1】:

Triple 在您想一次保存 3 个值并且可以传递不同的数据类型时很有用。如果您只是想学习,那么下面是它的用法示例,但如果您想在代码中使用,那么我建议您改用Objects。

public class Triple<T, U, V> {

    private final T first;
    private final U second;
    private final V third;

    public Triple(T first, U second, V third) {
        this.first = first;
        this.second = second;
        this.third = third;
    }

    public T getFirst() { return first; }
    public U getSecond() { return second; }
    public V getThird() { return third; }
}

这就是你可以实例化它的方式:

List<Triple<String, Integer, Integer>> = new ArrayList<>();

编辑

如cmets中所述,请注意它属于org.apache.commons.lang3.tuple,它不是Java中的内置类。

【讨论】:

  • 这比尝试使用类更有效吗?
  • @cody.tv.weber 我不认为它更有效。我认为这只是 Apache Commons 提供的一个方便的类
  • 那么这本质上会类似于 Golang 的多值返回吗?好的,我想这可能很方便。
【解决方案2】:

认为“元组”有 3 个值!

许多编程语言都提供了有效处理“固定”长度但每个条目类型不同的列表的方法。

Triple 类是为您提供类似功能的 Java 方式。像一对,但多了一个条目。

在其核心,固定长度元组允许您基于某种“排序”“松散耦合”不同类型的多个值。

【讨论】:

    【解决方案3】:

    当您需要一个数据结构来处理三个实体的列表时,您可以使用非常方便的 Triple。我写一个例子:

    import java.util.ArrayList;
    import java.util.List;
    import org.apache.commons.lang3.tuple.Triple;
    
    public class test2 {
    
    public static void main(String[] args) {
        
        List<Triple<Integer, String, String>> tripleList = new ArrayList<>();
        tripleList.add(Triple.of(100, "Japan", "Tokyo"));
        tripleList.add(Triple.of(200, "Italy", "Rome"));
        tripleList.add(Triple.of(300, "France", "Paris"));
        for(Triple<Integer, String, String> triple : tripleList) {
            System.out.println("triple left ="+ triple.getLeft());
            System.out.println("triple right= "+ triple.getRight() );
            System.out.println("triple middle = "+ triple.getMiddle() );
        }
    }
    
    }
    

    输出如下图所示:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-08
      • 2011-08-12
      • 1970-01-01
      • 2011-12-05
      • 2015-06-08
      • 1970-01-01
      • 2022-06-13
      相关资源
      最近更新 更多