2016-07-04 93 views
0

举一个简单的个人练习,我要做到以下几点:爪哇 - 对象池相同的参考

  • 创建一个类,它代表
  • 这个类的没有两个对象一个整数值与相同的整数值应该在任何时刻存在时间

这是我如何处理这个问题:

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()

+1

任何理由不使用'地图<整数,MyClass的>'? – Amit

回答

3

假设你正在使用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); 
    } 
} 
+1

或'computeIfAbsent(value,MyClass :: new)'。 –

+0

你可以请一点点,这个神奇的线是什么? 'synchronized','computeIfAbsent' + * LambdaMagic * ... – Matthias

+0

['computeIfAbsent'](https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#computeIfAbsent-K -java.util.function.Function-)在方法的Javadoc中描述。 'synchronized'是必须的,因为它是一个HashMap,[“如果多个线程同时访问一个哈希映射,并且至少有一个线程在结构上修改了映射,它必须在外部同步。”](https://docs.oracle的.com/JavaSE的/ 8 /文档/ API/JAVA/util的/ HashMap.html)。如果密钥当前不在地图中,那么lambda只是创建新实例的一件事情。 –

2

任何东西只要使用Map<Integer, MyClass>

+0

我可以在6分钟内接受答案。尽管如此,我对下面的答案感到兴奋。 – Matthias

+0

@Matthias - 确保你明白这一点..我不想让事情复杂化,但是因为它在那里...... – Amit