有 Java 编程相关的问题?

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

java创建唯一的增量id并将其添加到集合中

问题是,我需要为每个新客户创建新的增量ID,并将其添加到集合中,我正在尝试使用while循环,但它似乎不正确

public class Bank {

    private String name;

    private Set<Customer> customers = new HashSet<Customer>();


    private Set<AbstractAccount> accounts = new HashSet<AbstractAccount>();

    private Integer lastCustomerId = 0;

    private Integer lastAccountId = 0;

    public Integer addCustomer(String firstName, String lastName) {
        // generate id from lastCustomerId and increment it
        // add to Set
        return lastCustomerId++; 
    }

    public Integer addAccount(Integer ownerId, AccountType type) {
        // add to Set
    }       



}

共 (1) 个答案

  1. # 1 楼答案

    我不确定这是不是你想要的

    public class Bank
    {
    
        private String name;
    
       private Set<Customer> customers = new HashSet<Customer>();
    
    
        private Set<AbstractAccount> accounts = new HashSet<AbstractAccount>();
    
    
        private static int lastCustomerId = 0;
        private static int lastAccountId = 0;
    
        public static int GetNextCustomerID()
        {
            lastCustomerId++;
            return lastCustomerId;
        }
    
        public static int GetNextAccountID()
        {
            lastAccountId++;
            return lastAccountId;
        }
    
        public int addCustomer(String firstName, String lastName) 
        {
           // generate id from lastCustomerId and increment it
            int customerId = GetNextCustomerID();
            // add to Set
        }
    
        public int addAccount(int ownerId, AccountType type) 
        {
            // add to Set
            int accountId = GetNextAccountID();
        }   
    }