举一个简单的个人练习,我要做到以下几点:爪哇 - 对象池相同的参考
- 创建一个类,它代表
- 这个类的没有两个对象一个整数值与相同的整数值应该在任何时刻存在时间
这是我如何处理这个问题:
public class MyClass {
// Static pool
private static HashSet<MyClass> pool;
// Integer value each object holds
private int value;
static {
pool = new HashSet<MyClass>();
}
// private Constructor
private MyClass(int value) {
this.value = value;
}
// Static public method to create MyClass objects
public MyClass create(int value) {
// Create tmp object with private constructor
MyClass tmp = new MyClass(value);
// At this point I want to check, whether an object with the
// same integer value exists in the HashSet.
// If this is the case I would like to return a reference to
// the object in the HashSet (the GC will remove tmp).
// Otherwise I would like to add tmp to the HashSet and return
// a reference to tmp.
}
}
问题的一部分是作为上述代码中评论的一部分编写的。我很好奇以下事情。如果我不覆盖equals(Object obj)
,pool.contains(tmp)
将始终返回false(因为从Object
继承的默认equals(Object obj)
作为参考测试,我可以覆盖equals(Object obj)
以比较对象的value
-字段,但是如何从HashSet中获取引用??回到它
我需要做hashcode()
任何理由不使用'地图<整数,MyClass的>'? – Amit