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
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).
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)
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.
Objects of singleton class always return same hashcode. Please find below code snippet,
#Singleton class
public class StaticBlockSingleton {
//Static instance
private static StaticBlockSingleton instance;
public int i;
//Private constructor so that class can't be instantiated
private StaticBlockSingleton(){}
//static block initialization for exception handling
static {
try{
instance = new StaticBlockSingleton();
}catch(Exception e){
throw new RuntimeException("Exception occured in creating singleton instance");
}
}
public static StaticBlockSingleton getInstance(){
return instance;
}
public void printI(){
System.out.println("------ " + i);
}
}
#Singletone Client
public static void main(String[] arg) {
System.out.println("From Main");
StaticBlockSingleton s1 = StaticBlockSingleton.getInstance();
s1.i = 100;
System.out.println("S1 hashcode --- " + s1.hashCode());
StaticBlockSingleton s2 = StaticBlockSingleton.getInstance();
s2.i = 200;
System.out.println("S2 hashcode --- " + s2.hashCode());
s1.printI();
s2.printI();
}
#Output
From Main
S1 hashcode --- 1475686616
S2 hashcode --- 1475686616
------ 200
------ 200
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().