开发者

When using HashMap<ObjectA,ObjectB> in java , what is the type of the key?

When using a HashMap, will the hashmap st开发者_JAVA百科ore the entire objectA as a key , or will it only use the objectA.hashCode() as the key , thus resulting in an actual hashmap of int->ObjectB ?


It will store the reference to the key and the hash code at the time of insertion.

The idea is that when you try to look up an entry by key, the hash code is used to quickly get to a list of candidate keys, and then each candidate is checked via equality.


When using a HashMap, will the hashmap store the entire objectA as a key

Yes whole object as key

It will use key's hashCode() internally to store Value

Lets look into code

@Override
  461       public V get(Object key) {
  462           Entry<K, V> m = getEntry(key);
  463           if (m != null) {
  464               return m.value;
  465           }
  466           return null;
  467       }
  468   
  469       final Entry<K, V> getEntry(Object key) {
  470           Entry<K, V> m;
  471           if (key == null) {
  472               m = findNullKeyEntry();
  473           } else {
  474               int hash = computeHashCode(key);
  475               int index = hash & (elementData.length - 1);
  476               m = findNonNullKeyEntry(key, index, hash);
  477           }
  478           return m;
  479       }

           final Entry<K,V> findNonNullKeyEntry(Object key, int index, int keyHash) {
  482           Entry<K,V> m = elementData[index];
  483           while (m != null
  484                   && (m.origKeyHash != keyHash || !areEqualKeys(key, m.key))) {
  485               m = m.next;
  486           }
  487           return m;
  488       }


It will use the entire object.


Generally it uses the hash to find the entry but the entry itself contains both, the value and the key. That way you can call HashMap#values() to get a Set<Entry<key_type, value_type>> which contains the keys as well.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜