Java - 具有相同引用的对象池

Java - Object-Pool with same references

作为一个简单的个人练习,我想做以下事情:

我是这样处理问题的:

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) 将始终 return false(因为默认 equals(Object obj) 继承自 Object 测试以供参考。我可以覆盖 equals(Object obj) 来比较对象的 value 字段,但是我如何从 HashSet 中获取对 return 的引用?

我需要用 hashcode() 做些什么吗?

只需使用 Map<Integer, MyClass>.

假设您使用的是 Java 8,请使用 Map<Integer, MyClass>:

private static Map<Integer, MyClass> map = new HashMap<>();

然后,在你的方法中:

public MyClass create(int value) {
  synchronized (map) {
    return map.computeIfAbsent(value, MyClass::new);
  }
}