初学者问题:我有一个将整数数组存储为值的哈希图。每个值的键是一个由两个整数(坐标)组成的对象。

我的问题:如何根据对象(我的“键”)中的两个坐标从哈希图中检索值?

我的Coords类(在Eclipse的帮助下):

    public class Coords {
    int x;
    int y;

    public Coords(int x, int y) {
        super();
        this.x = x;
        this.y = y;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + x;
        result = prime * result + y;
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Coords other = (Coords) obj;
        if (x != other.x)
            return false;
        if (y != other.y)
            return false;
        return true;
    }

}


构建哈希图:

public class BuildMap {

public Coords coords;
public int[] someData = new int[4];
public Random random = new Random();
HashMap<Coords, int[]> map = new HashMap<Coords, int[]>();

public void buildHashMap() {

    // coordinates from (0,0) to (31,31)
    for (int i = 0; i < 32; i++) {
        for (int j = 0; j < 32; j++) {

            coords = new Coords(i, j);

            // Every Coord gets a few random numbers
            for (int k = 0; k < 4; k++) {
                someData[k] = random.nextInt(8564);
            }

            map.put(coords, someData);

        }
    }


如果要访问坐标12,13上的数组,如何检索它?是否需要迭代(我希望不是,我想添加100,000+坐标并快速访问课程)。

我希望这会在某种程度上起作用

int[] theValues = map.get(new Coords(12,13));


我希望你能帮助我。提前致谢!

最佳答案

问题在于如何构造地图。

您将添加与每个元素的值相同的数组。

您需要为每个元素实例化一个新数组。

for (int i = 0; i < 32; i++) {
    for (int j = 0; j < 32; j++) {

        coords = new Coords(i, j);
        int[] someData = new int[4];   // <==== create a new array for each Map value
        // Every Coord gets a few random numbers
        for (int k = 0; k < 4; k++) {
            someData[k] = random.nextInt(8564);
        }

        map.put(coords, someData);

    }

关于java - Java Hashmap从对象键获取值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17579634/

10-14 17:17
查看更多