【问题标题】:Create unique incremental id and add it to the set创建唯一的增量 id 并将其添加到集合中
【发布时间】:2013-11-28 22:19:46
【问题描述】:

问题是我需要为每个新客户创建新的增量 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
    }       



}

【问题讨论】:

  • 你的while循环在哪里?
  • 你已经声明了 lastCustomerId 和 lastAccountId,我猜就是因为这个原因。所以使用它们。添加新客户时,增加 lastCustomerId 并返回它。添加新帐户时,请以此类推。真正的问题是什么?
  • 一分钟 - 我会添加它
  • 目的是创建一个自动方法 - 添加新客户时,应创建 id 并将此客户添加到集合中
  • user3047466 编辑你的问题,不要粘贴 cmets 来澄清问题。

标签: java set unique-id


【解决方案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();
    }   
}

【讨论】:

  • 是的,这就是我要找的,否则应该添加 return customerId。然后我需要将它添加到集合中,但我尝试过 add(new Customer(customerId, firstName, lastName)); - 但它不起作用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-28
  • 2019-12-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多