有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

面向对象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) 个答案

  1. # 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之类的工具来创建用户索引。您还应该考虑线程的安全性和性能。