Do I need to implement hashCode() and equals() methods?

前端 未结 4 962
伪装坚强ぢ
伪装坚强ぢ 2021-01-14 07:47

If I have a map and an object as map key, are the default hash and equals methods enough?

class EventInfo{

    private String name;
    private Map

        
4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-14 08:08

    Yes, you do. HashMaps work by computing the hash code of the key and using that as a base point. If the hashCode function isn't overriden (by you), then it will use the memory address, and equals will be the same as ==.

    If you're in Eclipse, it'll generate them for you. Click Source menu → Generate hashCode() and equals().

    If you don't have Eclipse, here's some that should work. (I generated these in Eclipse, as described above.)

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((info == null) ? 0 : info.hashCode());
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }
    
    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (!(obj instanceof EventInfo)) {
            return false;
        }
        EventInfo other = (EventInfo) obj;
        if (info == null) {
            if (other.info != null) {
                return false;
            }
        } else if (!info.equals(other.info)) {
            return false;
        }
        if (name == null) {
            if (other.name != null) {
                return false;
            }
        } else if (!name.equals(other.name)) {
            return false;
        }
        return true;
    }
    

提交回复
热议问题