在Java中将三元组映射到int的最佳方法

时间:2017-11-29 14:53:39

标签: java

我想将Triplets映射到Int,就像这样:

height

我需要能够访问Int和三元组中的每个单独的值。

在Java中最有效的方法是什么?

由于

2 个答案:

答案 0 :(得分:8)

Java有没有内置方法来表示元组

但你可以轻松地创建一个。只需看看这个简单的通用Triple类:

public class Triple<A, B, C> {
    private final A mFirst;
    private final B mSecond;
    private final C mThird;

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

    public A getFirst() {
        return this.mFirst;
    }

    public B getSecond() {
        return this.mSecond;
    }

    public C getThird() {
        return this.mThird;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + this.mFirst.hashCode();
        result = prime * result + this.mSecond.hashCode();
        result = prime * result + this.mThird.hashCode();
        return result;
    }

    @Override
    public boolean equals(final Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final Triple other = (Triple) obj;
        if (this.mFirst == null) {
            if (other.mFirst != null) {
                return false;
            }
        } else if (!this.mFirst.equals(other.mFirst)) {
            return false;
        }
        if (this.mSecond == null) {
            if (other.mSecond != null) {
                return false;
            }
        } else if (!this.mSecond.equals(other.mSecond)) {
            return false;
        }
        if (this.mThird == null) {
            if (other.mThird != null) {
                return false;
            }
        } else if (!this.mThird.equals(other.mThird)) {
            return false;
        }
        return true;
    }
}

该课程只保留三个值并提供 getters 。此外,它会通过比较所有三个值来覆盖equalshashCode

不要害怕equalshashCode的实施方式。它们是由 IDE 生成的(大多数 IDE 都能够执行此操作)。

然后,您可以使用Map创建映射,如下所示:

Map<Triple<Integer, Integer, Integer>, Integer> map = new HashMap<>();

map.put(new Triple<>(12, 6, 6), 1);
map.put(new Triple<>(1, 0, 6), 1);
map.put(new Triple<>(2, 3, 7), 0);

并通过Map#get访问它们:

Triple<Integer, Integer, Integer> key = ...
int value = map.get(key);

或者,您可以为Triple课程添加第四个值,例如id或类似的内容。或者建立一个Quadruple类。

为方便起见,您还可以创建像Triple#of这样的通用工厂方法,并将其添加到Triple类:

public static <A, B, C> Triple<A, B, C> of(final A first,
        final B second, final C third) {
    return new Triple<>(first, second, third);
}

然后,您可以使用它来创建Triple稍微更紧凑的实例。比较两种方法:

// Using constructor
new Triple<>(12, 6, 6);

// Using factory
Triple.of(12, 6, 6);

答案 1 :(得分:3)

您可以使用org.apache.commons.lang3.tuple.Triple

HashMap<Triple<Integer, Integer, Integer>, Integer> tripletMap = new HashMap<>();
tripletMap.put(Triple.of(12, 6, 6), 1);
相关问题