Java复习-equals和hashcode

来源:互联网 发布:idc网站php源码 编辑:程序博客网 时间:2024/05/16 17:47

equals和hashcode是Object类从存在的两个方法

equals存在的含义是比较两个对象的内容或者自定义的内容是否相等.

只要覆写了equals方法就必须覆写hashcode方法.

hashcode方法存在的价值主要是为了hashmap,hashtable等map集合服务.

Object原生的equals方法就是比较两个对象的内存地址是否相同,这样的功能明显无法满足我们对于日常开发的需要.

如果我们需要进行深度比较就必须重写这个方法.

例如:在String类中equals方法就实现了比较字符串内容是否一致

public boolean equals(Object anObject) {
        if (this == anObject) {
            return true;
        }
        if (anObject instanceof String) {
            String anotherString = (String)anObject;
            int n = value.length;
            if (n == anotherString.value.length) {
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = 0;
                while (n-- != 0) {
                    if (v1[i] != v2[i])
                        return false;
                    i++;
                }
                return true;
            }
        }
        return false;
    }

public int hashCode() {
        int h = hash;
        if (h == 0 && value.length > 0) {
            char val[] = value;


            for (int i = 0; i < value.length; i++) {
                h = 31 * h + val[i];
            }
            hash = h;
        }
        return h;
    }

String重写的hashcode方法采用基数为31的原因是:

因为hash算法尽可能保证散列值均匀不重复且跨度角度

31是质数,乘积大小范围不会溢出.而且31可以通过(i>>5)-1实现效率较高


Demo自己完成的重写类:

equals方法保证:一致性,传递性,与空为false性

@Override
    public boolean equals(Object obj)
    {
      //这里使用number和name进行比较
        if (this == obj)
        {
            return true;
        }


        if (obj == null || this.getClass() != obj.getClass())
        {
            return false ;
        }


        StringCodes that = (StringCodes)obj;


        if (this.name.equals(that.name) && this.number == that.number)
        {
            return true;
        }


        return false ;


    }


覆写的hashcode

@Overridepublic int hashCode() {    int result = name != null ? name.hashCode() : 0;    result = 31 * result + number;    return result;}


原创粉丝点击