如何实现hashCode和equals方法 [英] How to implement hashCode and equals method

查看:116
本文介绍了如何实现hashCode和equals方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Java中为以下类实现 hashCode() equals()

How should I implement hashCode() and equals() for the following class in Java?

class Emp 
{
  int empid ; // unique across all the departments 
  String name;
  String dept_name ;
  String code ; // unique for the department 
}


推荐答案

在Eclipse中右键单击 - > source - >生成hashCode()和equals()给出:

in Eclipse right mouse click-> source -> generate hashCode() and equals() gives this:

/* (non-Javadoc)
 * @see java.lang.Object#hashCode()
 */
@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + (code == null ? 0 : code.hashCode());
    return result;
}
/* (non-Javadoc)
 * @see java.lang.Object#equals(java.lang.Object)
 */
@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (!(obj instanceof Emp))
        return false;
    Emp other = (Emp) obj;
    return code == null ? other.code == null : code.equals(other.code);
}

我选择了代码作为唯一字段

I've selected code as a unique field

这篇关于如何实现hashCode和equals方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆