温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

三元组在Java中的高效表达式

发布时间:2024-09-17 16:56:37 来源:亿速云 阅读:81 作者:小樊 栏目:编程语言

在 Java 中,一个三元组可以用一个包含三个元素的数组、列表或自定义类来表示。这里我将给出使用自定义类和使用 Apache Commons Lang 库的两种方法。

  1. 使用自定义类表示三元组:
public class Triple<A, B, C> {
    public final A first;
    public final B second;
    public final C third;

    public Triple(A first, B second, C third) {
        this.first = first;
        this.second = second;
        this.third = third;
    }

    // getter methods
    public A getFirst() {
        return first;
    }

    public B getSecond() {
        return second;
    }

    public C getThird() {
        return third;
    }
}

使用这个类,你可以创建一个三元组实例:

Triple<String, Integer, Double> triple = new Triple<>("Hello", 42, 3.14);
  1. 使用 Apache Commons Lang 库表示三元组(需要添加依赖):

首先,将 Apache Commons Lang 库添加到项目的依赖中。如果你使用 Maven,可以在 pom.xml 文件中添加以下依赖:

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

然后,你可以使用 Triple 类创建一个三元组实例:

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

public class Main {
    public static void main(String[] args) {
        Triple<String, Integer, Double> triple = ImmutableTriple.of("Hello", 42, 3.14);
    }
}

这两种方法都可以高效地表示三元组。使用自定义类的方法更简洁,而使用 Apache Commons Lang 库的方法更灵活。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI