2013年9月20日金曜日

Java Tripletクラス 3つの組みあわせ

2つの値を一つの組にまとめて比較やMapのキーにしたり
することがある場合は、

commons-langのTupleを使えばいいのですが
3つ必要 だという場合には自分で定義する必要があります。たぶん



Triplet.java:


import java.io.Serializable;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.builder.CompareToBuilder;

public class Triplet<X, Y, Z> implements Comparable<Triplet<X, Y, Z>>,Serializable {

    private static final long serialVersionUID = -7986546850125833527L;

    public X x;

    public Y y;

    public Z z;

    public static <X, Y, Z> Triplet<X, Y, Z> of(X x, Y y, Z z) {
        return new Triplet<X, Y, Z>(x, y, z);
    }

    public Triplet(X x, Y y, Z z) {
        this.x = x;
        this.y = y;
        this.z = z;
    }

    public X getX() {
        return x;
    }

    public void setX(X x) {
        this.x = x;
    }

    public Y getY() {
        return y;
    }

    public void setY(Y y) {
        this.y = y;
    }

    public Z getZ() {
        return z;
    }

    public void setZ(Z z) {
        this.z = z;
    }

    public int compareTo(Triplet<X, Y, Z> other) {
        return new CompareToBuilder().append(getX(), other.getX())
                .append(getY(), other.getY()).append(getZ(), other.getZ())
                .toComparison();
    }

    public boolean equals(Object obj) {
        if (obj == this) {
            return true;
        }
        if (obj instanceof Triplet<?, ?, ?>) {
            Triplet<?, ?, ?> other = (Triplet<?, ?, ?>) obj;
            return ObjectUtils.equals(getX(), other.getX())
                    && ObjectUtils.equals(getY(), other.getY())
                    && ObjectUtils.equals(getZ(), other.getZ());
        }
        return false;
    }
   
    public int hashCode() {
        // see Map.Entry API specification
        return (getX() == null ? 0 : getX().hashCode())
                ^ (getY() == null ? 0 : getY().hashCode())
                ^ (getZ() == null ? 0 : getZ().hashCode());
    }

    @Override
    public String toString() {
        return new StringBuilder().append('(').append(getX()).append(',')
                .append(getY()).append(',').append(getZ()).append(')').toString();
    }
}




commons-lang3が必要です。
Tupleを真似してみただけですが割りと使います^^;

3つのPKをもつデータをMapに登録するとか

0 件のコメント: