前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >面试必问hashCode和equals

面试必问hashCode和equals

作者头像
田维常
发布2019-08-28 15:25:56
3600
发布2019-08-28 15:25:56
举报

面试必问hashCode与equals

hashCode和equals用来标识对象,两个方法协同工作可用来判断两个对象是否相等。这两方法来源于:java.lang.Object

代码语言:javascript
复制
//本地方法
public native int hashCode();
public boolean equals(Object obj) {
        return (this == obj);
}

众所周知,根据生产的哈希将数据散列开来,可以是存取元素更快,对象通过调用Object.hashCode();生成哈希值;由于不可避免地存在哈希值冲突的情况,因此,当hashCode相同时,还需要进行equals方法比较,但是,若hashCode不同,将直接判定两个对象不相等,跳过equals,这加快了冲突处理效率。

Object类定义中对hashCode和equals要求如下:

代码语言:javascript
复制
如果两个对象的equals的结果相等,则两个对象的hashCode的返回结果必须是相同的。
如果两个兑现搞的hashCode相等,equals不一定相等,即就是两个对象不一定相等。
任何时候覆写equals,都必须同时覆写hashCode方法。

在Map和Set类集合中,用到这两个方法时,首先判断hashCode的值,如果hash值相等,则在判断equals的结果,HashMap中get方法判断如下:

代码语言:javascript
复制
if (e.hash == hash &&((k = e.key) == key
|| (key != null && key.equals(k))))
return e;

先进性hash值比较,然后进行equals比较。如果hash只不相等则equals方法都不用比较了。

这样一来就是要求hashCode方法要求就高了很多,一个优秀的哈希算法应尽可能地让元素均匀分布,降低冲突概念,即就是尽量在equals不相等的情况下hash值也不相等,这样使用&&或者||短路操作一旦生效,会极大地提高程序的执行效率。如果自定义Map的键,那么必须重写equals和hashCode方法。

此外,因为Set存储的是不重复的对象,依据hashCode和equals进行判断,所以Set存储的自定义对象也必须重写这两个方法。此时,如果重写equals而不重写hashCode,到底会有什么影响呢?

请看下面的代码:

代码语言:javascript
复制
public class Test {
    public static void main(String[] args) {
        Set<EqualsDemo> hashSet = new HashSet<>();
        hashSet.add(new EqualsDemo(1, "Java后端技术栈"));
        hashSet.add(new EqualsDemo(1, "Java后端技术栈"));
        hashSet.add(new EqualsDemo(1, "Java后端技术栈"));
        System.out.println(hashSet.size());
    }
}

输出结果:3

看源码发现Object中的hashCode方法是native方法:

代码语言:javascript
复制
 public native int hashCode();

那就只能去看虚拟机中的源码了,源码下载地址:

openJDK 7下载地址1:http://download.java.net/openjdk/jdk7

网上找找比什么盘,CSDN上都可以找到,并且下载的快,自己看着办咯。

进入openjdk\jdk\src\share\classes\java\lang目录下,可以看到 Object.java源码,打开

代码语言:javascript
复制
/*
 * Class:     java_lang_Object
 * Method:    hashCode
 * Signature: ()I
 */
JNIEXPORT jint JNICALL Java_java_lang_Object_hashCode
  (JNIEnv *, jobject);

打开openjdk\jdk\src\share\native\java\lang\目录,查看Object.c文件,可以看到hashCode()的方法被注册成有JVM_IHashCode方法指针来处理:

代码语言:javascript
复制
#include <stdio.h>
#include <signal.h>
#include <limits.h>
 
#include "jni.h"
#include "jni_util.h"
#include "jvm.h"
 
#include "java_lang_Object.h"
 
static JNINativeMethod methods[] = {
    //hashcode的方法指针JVM_IHashCode
    {"hashCode",    "()I",                    (void *)&JVM_IHashCode},
    {"wait",        "(J)V",                   (void *)&JVM_MonitorWait},
    {"notify",      "()V",                    (void *)&JVM_MonitorNotify},
    {"notifyAll",   "()V",                    (void *)&JVM_MonitorNotifyAll},
    {"clone",       "()Ljava/lang/Object;",   (void *)&JVM_Clone},
};

JVM_IHashCode方法指针在 openjdk\hotspot\src\share\vm\prims\jvm.cpp中定义,如下:

代码语言:javascript
复制
JVM_ENTRY(jint, JVM_IHashCode(JNIEnv* env, jobject handle))
  JVMWrapper("JVM_IHashCode");
  // as implemented in the classic virtual machine; return 0 if object is NULL
  return handle == NULL ? 0 : ObjectSynchronizer::FastHashCode (THREAD, JNIHandles::resolve_non_null(handle)) ;
JVM_END

如上可以看出,JVM_IHashCode方法中调用了ObjectSynchronizer::FastHashCode方法

ObjectSynchronizer::fashHashCode()方法在 openjdk\hotspot\src\share\vm\runtime\synchronizer.cpp文件中实现。

代码语言:javascript
复制
// hashCode() generation :
//
// Possibilities:
// * MD5Digest of {obj,stwRandom}
// * CRC32 of {obj,stwRandom} or any linear-feedback shift register function.
// * A DES- or AES-style SBox[] mechanism
// * One of the Phi-based schemes, such as:
//   2654435761 = 2^32 * Phi (golden ratio)
//   HashCodeValue = ((uintptr_t(obj) >> 3) * 2654435761) ^ GVars.stwRandom ;
// * A variation of Marsaglia's shift-xor RNG scheme.
// * (obj ^ stwRandom) is appealing, but can result
//   in undesirable regularity in the hashCode values of adjacent objects
//   (objects allocated back-to-back, in particular).  This could potentially
//   result in hashtable collisions and reduced hashtable efficiency.
//   There are simple ways to "diffuse" the middle address bits over the
//   generated hashCode values:
//
 
static inline intptr_t get_next_hash(Thread * Self, oop obj) {
  intptr_t value = 0 ;
  if (hashCode == 0) {
     // This form uses an unguarded global Park-Miller RNG,
     // so it's possible for two threads to race and generate the same RNG.
     // On MP system we'll have lots of RW access to a global, so the
     // mechanism induces lots of coherency traffic.
     value = os::random() ;
  } else
  if (hashCode == 1) {
     // This variation has the property of being stable (idempotent)
     // between STW operations.  This can be useful in some of the 1-0
     // synchronization schemes.
     intptr_t addrBits = intptr_t(obj) >> 3 ;
     value = addrBits ^ (addrBits >> 5) ^ GVars.stwRandom ;
  } else
  if (hashCode == 2) {
     value = 1 ;            // for sensitivity testing
  } else
  if (hashCode == 3) {
     value = ++GVars.hcSequence ;
  } else
  if (hashCode == 4) {
     value = intptr_t(obj) ;
  } else {
     // Marsaglia's xor-shift scheme with thread-specific state
     // This is probably the best overall implementation -- we'll
     // likely make this the default in future releases.
     unsigned t = Self->_hashStateX ;
     t ^= (t << 11) ;
     Self->_hashStateX = Self->_hashStateY ;
     Self->_hashStateY = Self->_hashStateZ ;
     Self->_hashStateZ = Self->_hashStateW ;
     unsigned v = Self->_hashStateW ;
     v = (v ^ (v >> 19)) ^ (t ^ (t >> 8)) ;
     Self->_hashStateW = v ;
     value = v ;
  }
 
  value &= markOopDesc::hash_mask;
  if (value == 0) value = 0xBAD ;
  assert (value != markOopDesc::no_hash, "invariant") ;
  TEVENT (hashCode: GENERATE) ;
  return value;
}
//   ObjectSynchronizer::FastHashCode方法的实现,该方法最终会返回我们期望已久的hashcode
intptr_t ObjectSynchronizer::FastHashCode (Thread * Self, oop obj) {
  if (UseBiasedLocking) {
    // NOTE: many places throughout the JVM do not expect a safepoint
    // to be taken here, in particular most operations on perm gen
    // objects. However, we only ever bias Java instances and all of
    // the call sites of identity_hash that might revoke biases have
    // been checked to make sure they can handle a safepoint. The
    // added check of the bias pattern is to avoid useless calls to
    // thread-local storage.
    if (obj->mark()->has_bias_pattern()) {
      // Box and unbox the raw reference just in case we cause a STW safepoint.
      Handle hobj (Self, obj) ;
      // Relaxing assertion for bug 6320749.
      assert (Universe::verify_in_progress() ||
              !SafepointSynchronize::is_at_safepoint(),
             "biases should not be seen by VM thread here");
      BiasedLocking::revoke_and_rebias(hobj, false, JavaThread::current());
      obj = hobj() ;
      assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
    }
  }
 
  // hashCode() is a heap mutator ...
  // Relaxing assertion for bug 6320749.
  assert (Universe::verify_in_progress() ||
          !SafepointSynchronize::is_at_safepoint(), "invariant") ;
  assert (Universe::verify_in_progress() ||
          Self->is_Java_thread() , "invariant") ;
  assert (Universe::verify_in_progress() ||
         ((JavaThread *)Self)->thread_state() != _thread_blocked, "invariant") ;
 
  ObjectMonitor* monitor = NULL;
  markOop temp, test;
  intptr_t hash;
  markOop mark = ReadStableMark (obj);
 
  // object should remain ineligible for biased locking
  assert (!mark->has_bias_pattern(), "invariant") ;
 
  if (mark->is_neutral()) {
    hash = mark->hash();              // this is a normal header
    if (hash) {                       // if it has hash, just return it
      return hash;
    }
    hash = get_next_hash(Self, obj);  // allocate a new hash code
    temp = mark->copy_set_hash(hash); // merge the hash code into header
    // use (machine word version) atomic operation to install the hash
    test = (markOop) Atomic::cmpxchg_ptr(temp, obj->mark_addr(), mark);
    if (test == mark) {
      return hash;
    }
    // If atomic operation failed, we must inflate the header
    // into heavy weight monitor. We could add more code here
    // for fast path, but it does not worth the complexity.
  } else if (mark->has_monitor()) {
    monitor = mark->monitor();
    temp = monitor->header();
    assert (temp->is_neutral(), "invariant") ;
    hash = temp->hash();
    if (hash) {
      return hash;
    }
    // Skip to the following code to reduce code size
  } else if (Self->is_lock_owned((address)mark->locker())) {
    temp = mark->displaced_mark_helper(); // this is a lightweight monitor owned
    assert (temp->is_neutral(), "invariant") ;
    hash = temp->hash();              // by current thread, check if the displaced
    if (hash) {                       // header contains hash code
      return hash;
    }
    // WARNING:
    //   The displaced header is strictly immutable.
    // It can NOT be changed in ANY cases. So we have
    // to inflate the header into heavyweight monitor
    // even the current thread owns the lock. The reason
    // is the BasicLock (stack slot) will be asynchronously
    // read by other threads during the inflate() function.
    // Any change to stack may not propagate to other threads
    // correctly.
  }
 
  // Inflate the monitor to set hash code
  monitor = ObjectSynchronizer::inflate(Self, obj);
  // Load displaced header and check it has hash code
  mark = monitor->header();
  assert (mark->is_neutral(), "invariant") ;
  hash = mark->hash();
  if (hash == 0) {
    hash = get_next_hash(Self, obj);
    temp = mark->copy_set_hash(hash); // merge hash code into header
    assert (temp->is_neutral(), "invariant") ;
    test = (markOop) Atomic::cmpxchg_ptr(temp, monitor, mark);
    if (test != mark) {
      // The only update to the header in the monitor (outside GC)
      // is install the hash code. If someone add new usage of
      // displaced header, please update this code
      hash = test->hash();
      assert (test->is_neutral(), "invariant") ;
      assert (hash != 0, "Trivial unexpected object/monitor header usage.");
    }
  }
  // We finally get the hash
  return hash;
}

以上这么多代码的核心部分:

代码语言:javascript
复制
mark=monitor->header;
asset(mark->is_neutral(),"invariant");
hash=mark->hash();
intptr_t hash() const{
    return mask_bits(value()>>hash_shift,hash_mask);
}

这里也就印证了:hashCode就是根据对象的地址进行相关计算得到int类型数值的。

上面EqualsDemo没有写hashCode,所以导致最后的结果是3,如果不想存储重复的元素,那么需要在EqualsDemo类中重写hashCode方法,代码如下:

代码语言:javascript
复制
    @Override
    public int hashCode() {
        return id+ name.hashCode();
    }

最后运行Test类,得出的结果:1

因为上面的name是String类型,并且String类重写了hashCode方法了,所以这里就直接使用了。

equals的实现方式与类的具体业务逻辑有关,但又各不相同,因而应尽量分享源码来确定其判断结果,比如下面的代码:

代码语言:javascript
复制
public class MyListDemo {
    public static void main(String[] args) {
        LinkedList<Integer> linkedList = new LinkedList<>();
        linkedList.add(1);
        ArrayList<Integer> arrayList = new ArrayList<>();
        arrayList.add(1);
        if (linkedList.equals(arrayList)) {
            System.out.println("equal");
        } else {
            System.out.println("not equal");
        }
    }
}

输出:equal

两个不同的集合,结果输出相等。让我们来看看这两个集合的equals方法是怎么实现的:

看其源码发现两个集合都是使用AbstractList中的equals方法(JDK版本是1.8),每个版本可能有差别。

面试题

两个对象的equals为true,则两个对象的hashCode相等。

两个对象的hashCode相等,两个对象的equals不一定为true。

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-08-27,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Java后端技术栈 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档