• hashCode()和equals()


    先看源码

    Object:

      public native int hashCode();

      public boolean equals(Object obj) {
          return (this == obj);
         }

    String:

      public int hashCode() {
        int h = hash;
            int len = count;
        if (h == 0 && len > 0) {
            int off = offset;
            char val[] = value;

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

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

    Integer:

    public int hashCode() {
        return value;
        }

     public boolean equals(Object obj) {
        if (obj instanceof Integer) {
            return value == ((Integer)obj).intValue();
        }
        return false;
        }

    可以知道String重写了Object的hashcode()和equals(),

    ==比较的是2个对象的地址,而equals比较的是2个对象的内容

  • 相关阅读:
    获得 Web Service 方法的描述信息
    make menuconfig 报错
    汇编调用c函数为什么要设置栈
    UBoot Makefile文件分析
    UBoot启动过程完全分析(转)
    (转)在fedora12下用crosstoolng建立armlinux交叉编译环境
    UBoot编译过程完全分析(转)
    雷军:给互联网创业者的“七字”建议
    uboot根目录下makefile
    Redhat 5 配置Samba服务器
  • 原文地址:https://www.cnblogs.com/ChenLLang/p/6039236.html
Copyright © 2020-2023  润新知