How to make an effective hashCode?

I have three hashCode methods, as described below, I have determined their priority by their effectiveness. I am wondering if there is another way to make the hashCode method more efficient.

1) public int hashCode() { //terrible
     return 5; 
   }
2) public int hashCode() { //a bit less terrible
     return name.length; 
   }
3) public int hashCode() { //better
     final int prime = 31;
     int result = 1;
     result = prime * result + ((name == null) ? 0 : name.hashCode());
     return result;
   }
+4
source share
5 answers

There is no reliable way to ensure that your function is hashcodeoptimal, as it is measured by two different metrics.

  • Efficiency . How to quickly calculate.
  • Clashes . What is the probability of a collision.

Your

  • Maximizes efficiency through collisions.
  • Finds a place somewhere in the middle - but still not good.
  • , - - .

.

, , (, ordinal enum).

- , - . , .

. , File HashMap. :

  • - .
  • - .
  • crc .
  • - SHA1 .

hashcode HashMap. - , . , , , , , , , .

. WikiPedia Hash Table , HashMap.

+6

- "" hashCode, . - HashMap, -.

, , , , . , .

+4

- , : hashCode()?

, , ?

""... - , ? , , , , ... ?

. , , , .

+2

:


3):

public int hashCode() {
     return Objects.hashCode(name);
}

, .


4.) , , . -, String, String . , 4:

// Changing this...
Map<Key, Value> map;
map.put(key, value);
Value value = map.get(key);

// ... to this:
Map<String, Value> map;
map.put(key.getName(), value);
Value value = map.get(key.getName());

( , "" Key , - . )


5.) , -. java.lang.String:

public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence {
    ...

    /** Cache the hash code for the string */
    private int hash; // Default to 0

, , . , Map "" , , , , t.

, , , , , , - :

class Key 
{
    private final String name;
    ... // Other fields...

    private final int hashCode;

    Key(String name, ...)
    {
        this.name = name;
        ... // Other fields

        // Pre-compute and store the hash code:
        this.hashCode = computeHashCode();
    }


    private int computeHashCode()
    {
        int result = 31;
        result = 31 * result + Objects.hashCode(name);
        result = 31 * result + ... // Other fields
        return result;
    }
}
+2
0

All Articles