Algorithm for obtaining a unique and the same hash code for an object when the application is run multiple times

I am using Java. I want to know if any algorithm is available that will give me a unique and the same hash code when I run the application several times to avoid a hash code collision.

I know that for similar objects jvm returns the same hash code, and for different objects it can return the same or different hash code. Bt I want some kind of logic to help generate a unique hash code for each object.

unique means that the hash code of one object must not collide with any other hash code of the object. And also, when I launch the application several times, it should return the same hash code to me, no matter what it returned to me earlier

+3
source share
3 answers

The default hash function in Java can return different hash codes for each JVM activation, since it is able to use the object's memory address, cripple it and return it.

This, however, is not a good coding practice, since objects that are equal should always return the same hash code! Please check the hash code to find out more. And most classes in Java already have a hashcode function that returns the same value every time the JVM is called.

: , - , equals hashcode. Eclipse IDE, , .

: IMHO Comparable <T> , SortedSets TreeMaps .

: , Serializable Cloneable.

+4

, - - - . , , -, .

:

  • , - . hashcode , hashcode , - .

  • , - , .

. - , - :

    static HashSet<Integer> usedCodes = ...
    static IdentityHashMap<YourClass, Integer> codeMap = ...

    public int hashcode() {
        Integer code = codeMap.get(this);
        if (code == null) {
            code = // generate value-based hashcode for 'this'
            while (usedCode.contains(code)) {
                code = rehash(code);
            }
            usedCodes.add(code);
            codeMap.put(this, code);
        }
        return code;
    }

- , sameness ... / - .

- usedCode codeMap . () - , , - -.

, , - . - . , , - , , - , .

FOLLOW UP

, URL- . URL- -, .

- . , , , . URL, -.

, -, . , () ... .

+1

...

, hashcode ( ), - . -, .

0

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


All Articles