溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

三元組在Java中的高效實現(xiàn)

發(fā)布時間:2024-09-16 15:20:39 來源:億速云 閱讀:82 作者:小樊 欄目:編程語言

在Java中,一個三元組(Triplet)通常表示為包含三個元素的數(shù)據(jù)結(jié)構(gòu)。要實現(xiàn)一個高效的三元組類,你可以使用泛型和不可變對象。這里是一個簡單的實現(xiàn):

public final class Triplet<A, B, C> {
    private final A first;
    private final B second;
    private final C third;

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

    public A getFirst() {
        return first;
    }

    public B getSecond() {
        return second;
    }

    public C getThird() {
        return third;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Triplet<?, ?, ?> triplet = (Triplet<?, ?, ?>) o;
        return Objects.equals(first, triplet.first) &&
                Objects.equals(second, triplet.second) &&
                Objects.equals(third, triplet.third);
    }

    @Override
    public int hashCode() {
        return Objects.hash(first, second, third);
    }

    @Override
    public String toString() {
        return "Triplet{" +
                "first=" + first +
                ", second=" + second +
                ", third=" + third +
                '}';
    }
}

這個實現(xiàn)使用了泛型,使得Triplet類可以容納任何類型的對象。同時,它是一個不可變對象,因為所有的字段都是final的,并且沒有提供修改字段值的方法。這有助于保證Triplet的安全性和性能。

此外,我們還重寫了equals()hashCode()toString()方法,以便在需要時能夠正確地比較和打印Triplet對象。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI