您好,登錄后才能下訂單哦!
在 Java 中,一個(gè)三元組可以用一個(gè)包含三個(gè)元素的數(shù)組、列表或自定義類來表示。這里我將給出使用自定義類和使用 Apache Commons Lang 庫的兩種方法。
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;
}
}
使用這個(gè)類,你可以創(chuàng)建一個(gè)三元組實(shí)例:
Triple<String, Integer, Double> triple = new Triple<>("Hello", 42, 3.14);
首先,將 Apache Commons Lang 庫添加到項(xiàng)目的依賴中。如果你使用 Maven,可以在 pom.xml
文件中添加以下依賴:
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
然后,你可以使用 Triple
類創(chuàng)建一個(gè)三元組實(shí)例:
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);
}
}
這兩種方法都可以高效地表示三元組。使用自定義類的方法更簡(jiǎn)潔,而使用 Apache Commons Lang 庫的方法更靈活。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。