为单例类
回答
如果它是单例,则不需要提供实现,因为无论它在哪里使用,它都将是相同的对象实例。缺省值(System.identityHashCode(obj))将是足够的,或者甚至只是一个常数(例如5)
我认为4是正确的随机数返回 http://stackoverflow.com/questions/84556/whats-your-favorite-programmer-卡通/ 84747#84747 – drvdijk 2009-07-10 09:49:33
顺便说一句,这里我们不需要一个随机数字。这将是一个矫枉过正的问题。 :) – 2009-07-10 10:05:01
由于只有一个对象,所以您不必担心使其他相等的对象具有相同的hashCode。所以你可以使用System.identityHashCode(即默认值)。
public int hashCode() {
return 42; // The Answer to the Ultimate Question of Life, The Universe and Everything
}
如果您使用singleton ENUM模式(Effective Java#??),您将获得hashCode和equals(免费)。
我不想在这里重复其他答案。所以是的,如果你使用的是Singleton,那么Matthew's answer就是你想要的。确保你没有把singleton与immutable 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()。
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
- 1. 为Actionscript实现单例类
- 2. Python单例类
- 3. 实例化单例类
- 4. 将RealmObject作为单例扩展的类
- 5. 设置为单个类的实例
- 6. 静态单例类成为空
- 7. 扩展单例类?
- 8. 单类实例C++
- 9. 单例类的几个例子
- 10. WebApplication有2个单例类的实例
- 11. 类中的类,实例化为单个对象
- 12. 如何将Log4Net包装类作为单例类?
- 13. 单独的日志文件为同一类的单独实例
- 14. Javascript单例类默认值
- 15. 使用单例类和sqlite
- 16. python中的单例类
- 17. mod_passenger,线程和单例类
- 18. 单个实例/基类
- 19. 嵌套的单例类
- 20. JavaScript - 什么是单例类?
- 21. C++单例模板类
- 22. 类别和单例教程
- 23. Java类的单个实例
- 24. java中的单例类API
- 25. Flex中的单例类
- 26. Java单例内部类
- 27. 派生类和单例
- 28. 为什么我们应该将“Logger”类作为单例考虑?
- 29. Google模拟一个单例类C++类
- 30. java单例类vs最终类
怎么样 “抛出新UnsupportedOperationException异常()” :) – skaffman 2009-07-10 09:49:26