单例类的hashCode实现

时间:2009-07-10 09:41:12

标签: java

的实施方式
public int hashCode()
{
}
单例类中的

方法?请为我提供实施

6 个答案:

答案 0 :(得分:11)

由于只有一个对象,因此您不必担心使其他相同的对象具有相同的hashCode。所以你可以使用System.identityHashCode(即默认值)。

答案 1 :(得分:5)

如果它是单例,则不需要提供实现,因为无论在何处使用它都将是相同的对象实例。默认(System.identityHashCode(obj))就足够了,甚至只是一个常数(例如5)

答案 2 :(得分:3)

public int hashCode() {
    return 42; // The Answer to the Ultimate Question of Life, The Universe and Everything
}

答案 3 :(得分:1)

如果您使用单例ENUM模式(Effective Java#??),您将获得hashCode并且等于免费。

答案 4 :(得分:1)

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

答案 5 :(得分:0)

我不想在此重复其他答案。所以,是的,如果你使用的是Singleton,那么Matthew's answer就是你想要的。确保您不会将singletonimmutable object混淆。如果你有一个不可变对象,那么你将不得不实现一个hashCode()方法。

请记住,最多只有一个单身实例。因此,默认的hashCode就足够了。

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; }
}

如果您使用的是不可变的,请不要忘记在覆盖hashCode()时覆盖equals()。