2015-02-09 106 views
2

我遇到了這個需求的問題。我有這個片段:Java自動增量問題

private String id; 
    private int age; 
    private static int index; 

    public Customer(int a) { 
      this.id = a + "C" + index; 
      index++; 
      this.age = a; 
    } 

它工作正常。但事情是,我希望每個年齡的指數都會重置爲1,如< 10C1,10C2>當有2個10歲的顧客時,如果您創建了20歲的新顧客,它將返回到< 20C1,20C2,...>。由於對年齡沒有限制,所以if語句似乎是不可能的。

+1

而不是保留一個靜態變量索引,你應該保留一個地圖,年齡作爲關鍵字,索引作爲值。 ConcurrentHashMap對此很有幫助。 – Thomas 2015-02-09 05:04:54

+1

使用地圖。或者創建你自己的數據結構。 – Kon 2015-02-09 05:05:06

+0

@Thomas:謝謝,我剛剛嘗試過ConcurrentHashMap,它現在可以工作:) – 2015-02-09 05:47:03

回答

1

在用戶使用靜態地圖:

private String id; 
private int age; 
private static map indexMap = new HashMap(); 

public Customer(int a) { 
     this.id = a + "C" + index; 
     index++; 
     this.age = a; 
} 

public synchronized static int getIndexOfAge(int age) { 
    if (!indexMap.contains(age)) { 
     indexMap.put(age, 1); 
    } 
    int theIndex = indexMap.get(age); 
    theIndex++; 
    indexMap.put(age, theIndex); 
} 

但我不得不說這是真的不代碼的好方法。你應該使用像UserIndexFactory這樣的東西來創建用戶索引。您還應該考慮線程的安全性和性能。

+0

感謝一大堆:D它只是一個練習。我現在工作:) – 2015-02-09 05:50:10