gpt4 book ai didi

Java自增问题

转载 作者:行者123 更新时间:2023-11-30 11:08:49 25 4
gpt4 key购买 nike

我在满足这个要求时遇到了问题。我有这个片段:

    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 语句似乎是不可能的。

最佳答案

在用户中使用静态 map :

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 的东西来创建用户索引。您还应该考虑线程安全和性能。

关于Java自增问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28403072/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com