在Java代码中如何重写equals和hashCode呢?
下文笔者讲述java代码重写equals和hashCode的示例分享,如下所示
equals和hashCode方法用途
当我们比较两个java对象时, 此时笔者建议大家重写equals和hashCode方法例:重写equals和hashCode方法的示例
User.java public class User { private String name; private int age; private String passport; //getters and setters, constructor @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof User)) { return false; } User user = (User) o; return user.name.equals(name) && user.age == age && user.passport.equals(passport); } //Idea from effective Java : Item 9 @Override public int hashCode() { int result = 17; result = 31 * result + name.hashCode(); result = 31 * result + age; result = 31 * result + passport.hashCode(); return result; } }
JDK 7及更高版本的重写方法
User.javaimport java.util.Objects; public class User { private String name; private int age; private String passport; //getters and setters, constructor @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof User)) { return false; } User user = (User) o; return age == user.age && Objects.equals(name, user.name) && Objects.equals(passport, user.passport); } @Override public int hashCode() { return Objects.hash(name, age, passport); } }
Apache Commons Lang中EqualsBuilder和HashCodeBuilder函数
User.javaimport org.apache.commons.lang3.builder; public class User { private String name; private int age; private String passport; //getters and setters, constructor @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof User)) { return false; } User user = (User) o; return new EqualsBuilder() .append(age, user.age) .append(name, user.name) .append(passport, user.passport) .isEquals(); } @Override public int hashCode() { return new HashCodeBuilder(17, 37) .append(name) .append(age) .append(passport) .toHashCode(); } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。