美文网首页
Java @Override hashCode() equals

Java @Override hashCode() equals

作者: 0bbe943b8a86 | 来源:发表于2018-10-15 00:59 被阅读0次

    Test有三个变量String的name,int的salary,double的weight

    public class Test {
    
        private final String name;
        private final int salary;
        private final double weight;
    

    Constructor

        public Test(String name, int salary, double weight) {
            this.name = name;
            this.salary = salary;
            this.weight = weight;
        }
    

    equals实现

        @Override public boolean equals(Object o) {
            if (this == o) {
                return true;
            }
            if (o == null || getClass() != o.getClass()) {
                return false;
            }
    
            Test test = (Test) o;
    
            if (name != null ? !name.equals(test.name) : test.name != null) {
                return false;
            }
            if (!Double.valueOf(weight).equals(Double.valueOf(test.weight))) {
                return false;
            }
            return salary == test.salary;
        }
    

    hashCode实现

        @Override public int hashCode() {
            int result = (name != null ? name.hashCode() : 0);
            result = 31 * result + salary;
            result = 31 * result + Double.valueOf(weight).hashCode();
            return result;
        }
    }
    

    相关文章

      网友评论

          本文标题:Java @Override hashCode() equals

          本文链接:https://www.haomeiwen.com/subject/bbjxzftx.html