String和equals()、hashCode()

Object中的“==”,equal,hashCode()

Object中的==

  • 对于基本数据类型,“==”比较值是否相同。
  • 对于引用数据类型, “==”比较内存中的存放地址是否相同。

Object中的equals()

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

Object的equals()方法默认还是根据“==”比较,所以比较的还是内存地址。

Object中的hashCode()

public int hashCode() {
    int lockWord = shadow$_monitor_;
    final int lockWordStateMask = 0xC0000000;  // Top 2 bits.
    final int lockWordStateHash = 0x80000000;  // Top 2 bits are value 2 (kStateHash).
    final int lockWordHashMask = 0x0FFFFFFF;  // Low 28 bits.
    if ((lockWord & lockWordStateMask) == lockWordStateHash) {
        return lockWord & lockWordHashMask;
    }
    return System.identityHashCode(this);
}

Object中的hashCode()返回值是在JVM中的32位地址。

String类的“==”,equal,hashCode()

String类中对hashCode()和equals()都进行了重写,所以调用String的equals()和hashCode()可能会和没重写这两个方法的类产生不同的结果。

String的equals()

@Override
public boolean equals(Object other) {
    if (other == this) {
      return true;
    }
    if (other instanceof String) {
        String s = (String)other;
        int count = this.count;
        if (s.count != count) {
            return false;
        }
        // TODO: we want to avoid many boundchecks in the loop below
        // for long Strings until we have array equality intrinsic.
        // Bad benchmarks just push .equals without first getting a
        // hashCode hit (unlike real world use in a Hashtable). Filter
        // out these long strings here. When we get the array equality
        // intrinsic then remove this use of hashCode.
        if (hashCode() != s.hashCode()) {
            return false;
        }
        for (int i = 0; i < count; ++i) {
            if (charAt(i) != s.charAt(i)) {
                return false;
            }
        }
        return true;
    } else {
        return false;
    }
}

同样是如果内存地址相同肯定内容也相同,返回true。
存储地址不同,要满足长度、hash码、对应的字符都相同才能返回true。

String的hashCode()

@Override public int hashCode() {
    int hash = hashCode;
    if (hash == 0) {
        if (count == 0) {
            return 0;
        }
        for (int i = 0; i < count; ++i) {
            hash = 31 * hash + charAt(i);
        }
        hashCode = hash;
    }
    return hash;
}

根据String的成员变量hashCode和字符串的内容生成hashcode。

总结:

默认情况下,==比较对象的存储地址,hashCode返回的事对象的存储地址。
equal比较对象,默认也是比较对象在JVM中的地址,同==
大多数类都根据自己的功能重写了equals(),但一般重写equals()就要覆盖hashCode(),重新定义散列码规范。

更详细的区别和通用约定请看Java中==和equals的区别,equals和hashCode的区别

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值