Search code examples
javagenericshashinterfacehash-code-uniqueness

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;

}

Solution

  • 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().