sny
sny

Reputation: 3

Java how to make the hash unique

I'm trying to create an abstract class Coin, having instance variables name (a String), symbol (of type java.awt.Image), and hash (a String.) The problem is that I need to make the attribute hash not the same as the one being returned by the default hashcode() method, hence having the hash of a Coin unique.

abstract class Coin {

    private String name;
    private Image symbol; 
    private String hash;

}

Upvotes: -2

Views: 2670

Answers (2)

nafas
nafas

Reputation: 5423

before I move on just let you know, a hash value may never be 100% unique because of hash collision.

having said that, I assume you want a unique String for variable hash(note hashCode() function in java is different as it returns an int)

there are many hashing algorithms, the one I normally use for unification in such scenario is MD5

There is an Apache utility called DiguestUtility which make life easy.

Here is an example of the use:

DigestUtils.md5(byte[] bytes);// --> returns a string of 32 char long
DigestUtils.md5(String s);// --> returns a string of 32 char long
...

Read through the methods in the documentation to see which one suits you more.

Upvotes: 0

Chinmay jain
Chinmay jain

Reputation: 999

You can override the default hashCode() function in the following way:

 @Override
public int hashCode() {
    // Unique hashcode generating function goes here
    return hash;
}

A way could be using name.hashCode()+symbol.hashCode().

Upvotes: -2

Related Questions