2016-07-04 96 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