what will be the implementation for
public int hashCode()
{
}
method in singleton class? Please do provide me the implementation
what will be the implementation for
public int hashCode()
{
}
method in singleton class? Please do provide me the implementation
If it's a singleton, you don't need to provide an implementation, as it will be the same object instance wherever it's used. The default (System.identityHashCode(obj)) will be sufficient, or even just a constant number (eg 5)
Since there's only one object, you don't have to worry about making other, equal, objects have the same hashCode. So you can just use System.identityHashCode (i.e. the default).
public int hashCode() {
return 42; // The Answer to the Ultimate Question of Life, The Universe and Everything
}
If you use the singleton ENUM pattern instead (Effective Java #??), you'll get hashCode and equals for free.
I don't want to repeat other answers here. So yes, if you are using a Singleton then Matthew's answer is what you want. Make sure you are not confusing singleton with just an immutable object. If you have an immutable object, then you will have to implement a hashCode() method.
Remember there is only ever at most one instance of a singleton. Therefore, the default hashCode is sufficient.
public class ImmutableNotSingleton {
private final int x;
public ImmutableNotSingleton(int x) { this.x = x; }
// Must implement hashCode() as you can have x = 4 for one object,
// and x = 2 of another
@Override public int hashCode() { return x; }
}
If you were using an immutable, don't forget to override equals() if when you override hashCode().