2015-02-09 108 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