2009-07-10 44 views
1

实施的hashCode会是怎样在单例类为单例类

public int hashCode() 
{ 
} 

方法的实施?请为我提供执行

+3

怎么样 “抛出新UnsupportedOperationException异常()” :) – skaffman 2009-07-10 09:49:26

回答

5

如果它是单例,则不需要提供实现,因为无论它在哪里使用,它都将是相同的对象实例。缺省值(System.identityHashCode(obj))将是足够的,或者甚至只是一个常数(例如5)

+4

我认为4是正确的随机数返回 http://stackoverflow.com/questions/84556/whats-your-favorite-programmer-卡通/ 84747#84747 – drvdijk 2009-07-10 09:49:33

+0

顺便说一句,这里我们不需要一个随机数字。这将是一个矫枉过正的问题。 :) – 2009-07-10 10:05:01

11

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

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

如果您使用singleton ENUM模式(Effective Java#??),您将获得hashCode和equals(免费)。

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

如果您正在使用的不可变的,不要忘记重写equals()如果当你重写了hashCode()。

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