HashMap,ArrayList <point>的初始化作为映射的值失败

时间:2017-06-24 18:18:58

标签: java arrays arraylist hashmap

我有一个名为Point的类,它有一个构造函数Point,其中包含x,y。

我有Point(key)和ArrayList(value)的映射, 初始化地图后,我的arrayLists仍为null,为什么会这样?

//Flip objects for the current player's choice
        Map<Point, ArrayList<Point>> flipMap = new HashMap<Point, ArrayList<Point>>();

//Init flipping map with keys
            for(int i = 0; i < 8; i++)
                for(int j = 0; j < 8; j++)
                    flipMap.put(new Point(i,j), new ArrayList<Point>());

ArrayList<Point> test;
            for(int i = 0; i < 8; i++){
                for(int j = 0; j < 8; j++){
                    if((test = flipMap.get(new Point(i,j))) == null);
                    test = new ArrayList<Point>();
                }
            }

问题 - 打印出null:

System.out.println(flipMap.get(new Point(0,0)));

2 个答案:

答案 0 :(得分:1)

您需要覆盖类Point上的hashcode和equals函数,以便hashmap正确存储并获取您的值。否则,对象仅相等,并且当它们是完全相同的对象时返回。

答案 1 :(得分:1)

你需要在Key上实现hashCode和equals,在你的例子中是Point类。这些方法的默认实现只是检查实例的相等性(换句话说,如果两个对象实际上是同一个对象,它们将是相等的。)在你的输入哈希映射和获取你创建新对象的情况下,所以默认实现将视为不同的密钥。您可以根据hashMap的大小进行验证。

<强>解决方案:

 public class Point {

    private int x;
    private int 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;
        Point other = (Point) obj;
        if (x != other.x)
            return false;
        if (y != other.y)
            return false;
        return true;
    }
}