Java中二维数组的替代方法

Java中二维数组的替代方法

问题描述:

我有一个查找表,应该被两个单独的键值访问。一个丑陋的方式是:

I have a lookup table that should be accessed by two separate key values. One ugly way to do this is:

int[][] myArray = new int[256][256];
myArray[key1][key2] = 25;

其中key1和key2是以前动态生成的键。但这是相当难看的。似乎更好的方法是使用地图,但这些需要一个单一的键,而不是两个。 Java本来不支持元组,那我应该用什么呢? (使用数组作为关键字也看起来很尴尬)。

where key1 and key2 are keys that were previously generated dynamically. But this is rather ugly. It seems that a better way to do this would be to use a Map, but those require a single key, not two. Java doesn't natively support tuples, so what should I use instead? (It also seems awkward to use an array as the key).

编辑:我说这不是特别漂亮的原因我的数组实际上由字符值引用,而不是整数。他们可以互换使用,但对我之前的问题的反应似乎也表明:

EDIT: The reason I say that this isn't particularly pretty is that my array is actually referenced by character values, not integers. They could be used interchangeably, but the responses to my previous question seem to suggest otherwise:

Java中的2D数组,由字符索引

p>什么是丑陋的?这就像2D矩阵可以在Java中一样简单,它也很快。

What's so ugly about that? That's about as simple as 2D matrices can be in Java, and it's quick, too.

如果你真的想使用一个地图,只需定义你自己的 Tuple 类用作键 - 但请确保您正确覆盖 equals() hashCode()!我建议实现一个不可变的 Tuple 类,因为使用可变对象作为地图键可能会导致严重的问题。

If you really want to use a map, just defined your own Tuple class to use as a key - but be sure that you override equals() and hashCode() correctly! I'd recommend implementing an immutable Tuple class because using mutable objects as map keys can cause serious issues.

package q5128376;

import java.util.Arrays;

public class Tuple<T>
{
    private T[] values;
    private int hashCode;

    private Tuple(T... values)
    {
        this.values = values;
        this.hashCode = hashCode(values);
    }

    public static <T> Tuple<T> create(T... values)
    {
        return new Tuple<T>(values);
    }

    private static <T> int hashCode(T... values)
    {
        return 31 * Arrays.hashCode(values);
    }

    @Override
    public int hashCode()
    {
        return hashCode;
    }

    @Override
    public boolean equals(Object obj) 
    {
        if (this == obj) return true;
        if (!(obj instanceof Tuple<?>)) return false;
        Tuple<?> other = (Tuple<?>) obj;
        if (!Arrays.equals(values, other.values)) return false;
        return true;
    }
}