【问题标题】:Java auto increment issueJava自动增量问题
【发布时间】:2015-04-08 19:07:55
【问题描述】:

我无法满足此要求。我有这个sn-p:

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

【问题讨论】:

  • 不要保留一个静态变量索引,您应该保留一张以年龄为键、索引为值的地图。 ConcurrentHashMap 将对此有好处。
  • 使用地图。或者创建自己的数据结构。
  • @Thomas:谢谢,我刚刚尝试了 ConcurrentHashMap,它现在可以工作了 :)
  • @Kon 谢谢你:D 这真的很有帮助

标签: java oop auto-increment


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

【讨论】:

  • 非常感谢 :D 这只是一个练习。我现在开始工作了:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-21
相关资源
最近更新 更多