Java HashMap.get() returns null when I create a new instance of an object as a key

后端 未结 3 1924
Happy的楠姐
Happy的楠姐 2020-12-22 01:41

I\'m making a spreadsheet application and I\'m using a HashMap to store the data in the cells. As the key I\'m using a Point class, which only has the number of rows and col

3条回答
  •  被撕碎了的回忆
    2020-12-22 02:21

    To detail my comment above, your Point class should implement hashcode and equals like following: (many implementations exist, it's just one that works) Supposing that your instance's variables are x and y.

        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
    
            Point point = (Point) o;
    
            if (x != point.x) return false;
            if (y != point.y) return false;
    
            return true;
        }
    
        public int hashCode() {
            int result = x;
            result = 31 * result + y;
            return result;
        }
    

    Otherwise, if you don't override those methods, Object's Javadoc explains well your issue:

    As much as is reasonably practical, the hashCode method defined by
         * class {@code Object} does return distinct integers for distinct
         * objects. (This is typically implemented by converting the internal
         * address of the object into an integer, but this implementation
         * technique is not required by the
         * JavaTM programming language.)
         *
         * @return  a hash code value for this object.
         * @see     java.lang.Object#equals(java.lang.Object)
         * @see     java.lang.System#identityHashCode
         */
        public native int hashCode();
    

    Thus, new Point(1,2) would not be considered as equal to new Point(1,2) and therefore, could never be retrieved from your Map.

提交回复
热议问题