Why are keys unrecoverable in Java?

I apologize for the rather naive question, but I believe that my own answer was naive. I think that the keys (in HashTables) are immutable, because we would not want to somehow accidentally change the key and, therefore, ruin the HashTable sort. Is this the correct explanation? If so, how can this be more correct?

+4
source share
3 answers

Over time, the HashTable.putkey is hashed, and its value is stored in one of several buckets (which are lists of key value pairs) based on the hash, for example, something like:

bucket[key.hashcode() % numberOfBuckets].add(key, value)

hashcode , , , - null get .

: - hashcode . hashcode . , , -. hashcode , .

public int hashcode { return 42; /*terrible hashcode example, don't use!*/ }

, -, :

public int hashcode {
    int hash = field1.hashcode();
    hash = hash*31 + field2.hashcode(); //note the prime 31
    hash = hash*31 + field3.hashcode();
    return hash;
}
+5

, .

HashTable , hashCode() ( equals), ( - , ).

, -: ​​ (key, value), - key , "" " . value key, hashCode , .

, hashCode , "bucket bucket" "", .

, Key, ( , , partOfHashCode hashCode/equals):

public static class Key {
  private String partOfHashCode;
  private String notPartOfHashCode;

  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((partOfHashCode == null) ? 0 : partOfHashCode.hashCode());
    return result;
  }
  @Override
  public boolean equals(Object obj) {
    if (this == obj)
      return true;
    if (obj == null)
      return false;
    if (getClass() != obj.getClass())
      return false;
    Key other = (Key) obj;
    if (partOfHashCode == null) {
      if (other.partOfHashCode != null)
        return false;
    } else if (!partOfHashCode.equals(other.partOfHashCode))
      return false;
    return true;
  }
}

:

public static void main(String[] args) {

Map<Key, String> myMap = new HashMap<>();
Key key = new Key();
key.partOfHashCode = "myHash";

myMap.put(key, "value");

key.notPartOfHashCode = "mutation of the key, but not of its hash/equals definition";

System.out.println(myMap.get(key));
}

( "" ).

public static void main(String[] args) {

  Map<Key, String> myMap = new HashMap<>();
  Key key = new Key();
  key.partOfHashCode = "myHash";

  myMap.put(key, "value");

  key.partOfHashCode = "mutation of the hashCode of the key";

  System.out.println(myMap.get(key));
}

( "" ).

hashCode/equals.

+3

Java , HashTable . , hashcode . hashcode, . , hashcode 1. -, 1. hashcode 2 hashMap.get(key). HashTable, , 2, . remove, .

tl; dr HashTable hashcode s, .

0

Source: https://habr.com/ru/post/1618385/


All Articles