使一个对象的字段对存储在数组列表中的每个对象都是唯一的。

问题描述 投票:0回答:2

所以,我有一个存储客户的数组列表,我的任务是让任何客户都不能有相同的ID。

代码有一个写法,写了一个所有客户的文本文件,所以我的任务是,当代码被关闭,客户已经被写入文件,当代码重新打开,新的客户,并添加到列表中,没有一个人可以有相同的ID谁已经从以前的客户存储在列表中的人。

下面是一些代码。

这是客户文本文件的写入数据。

public void writeCustomerData(String fileName)
throws FileNotFoundException
{
    PrintWriter pw = new PrintWriter(fileName);
    for (Customer c: customerList)
    {
        String lineOfOutput = c.getCustomerID() + ", " + c.getTitle() + ", " + c.getFirstName() + ", " + c.getSurname() + ", " + c.getInitials();
        pw.println(lineOfOutput);
    }
    pw.close();
}

这是添加新客户的构造函数

public Customer(String nSurname, String nFirstName, String nOtherInitials, String nTitle)
{
    customerID = "unknown";
    surname = nSurname;
    firstName = nFirstName;
    otherInitials = nOtherInitials;
    title = nTitle;
}

这是将客户存储到arrayList中的代码。

public void storeCustomer(Customer customer)
{
    if (customer.getCustomerID().equalsIgnoreCase("unknown"))
    {
        customer.generateCustomerID("AB", 5);
    }
    customerList.add(customer);
}

这是生成ID的代码。

public void generateCustomerID(String prefix, int length)
{
    Random random = new Random();
    int rand = 0;
    for (int i = 0; i < length; i++)
    {
        rand = random.nextInt(10);
        prefix = prefix + Integer.toString(rand);

    }
    setID(prefix);
}
java arraylist unique bluej
2个回答
0
投票

如果我理解正确,你需要实现你需要使用一个 Set ("一个不包含重复元素的集合")以避免重复。

所以,每次运行代码时,你必须从文件中读取所有的行,创建一个Customer,并将其存储在 Set.随着 Set,当你呼叫 customerList.add(customer) 套装本身会负责避免添加重复的内容。equalshashCode 以检查是否 Custom 已在 Set,所以一定要正确实现这些方法。


0
投票

在这种情况下,随机生成ID也许不是一个好的解决方案。

String uniqueID = UUID.randomUUID().toString();

它生成的是完全随机的字符串。

如果你真的只需要随机,最好使用 ThreadLocalRandom.current().nextInt()

© www.soinside.com 2019 - 2024. All rights reserved.