首页 > 学院 > 开发设计 > 正文

正确重写equals()和hashCode()方法

2019-11-06 07:16:59
字体:
来源:转载
供稿:网友

比较两个java对象时, 如果相同的对象有不同的hashCode,比较操作会出现意想不到的结果,为了避免这种问题,要同时复写equals方法和hashCode方法,而不要只写其中一个。

class People { String name; int age; public People(String name, int age) { this.age = age; this.name = name; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof People)) { return false; } People people = (People) obj; return people.name.equals(name) && people.age == age; } @Override public int hashCode() { int result = 17; result = 31 * result + name.hashCode(); result = 31 * result + age; return result; }}public class Main { public static void main(String[] args) { People people1 = new People("程", 22); People people2 = new People("程", 22); People people3 = new People("程", 13); System.out.PRintln(people1.equals(people2)); System.out.println(people1.equals(people3)); }}

运行结果

truefalse
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表