Java自动增量问题
我在这个要求上遇到了麻烦。我有一段话:Java自动增量问题,java,oop,auto-increment,Java,Oop,Auto Increment,我在这个要求上遇到了麻烦。我有一段话: private String id; private int age; private static int index; public Customer(int a) { this.id = a + "C" + index; index++; this.age = a; } 它很好用。但问题是,我希望每个年龄段的指数都会重置为1,比如当有2个10岁的客
private String id;
private int age;
private static int index;
public Customer(int a) {
this.id = a + "C" + index;
index++;
this.age = a;
}
它很好用。但问题是,我希望每个年龄段的指数都会重置为1,比如当有2个10岁的客户时,如果你创建了一个20岁的新客户,它会返回到。由于年龄没有限制,因此if语句似乎不可能使用。在用户中使用静态映射:
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之类的工具来创建用户索引。你也应该考虑线程的安全性和性能。代替保持一个静态变量索引,你应该保留一个以年龄为关键字和索引为值的映射。ConcurrentHashMap将适用于此。使用映射。或者创建您自己的数据结构。@Thomas:谢谢,我刚刚试过ConcurrentHashMap,现在可以使用了:)@Kon谢谢:D它真的很有用谢谢:D这只是一个练习。我现在让它工作了:)