gpt4 book ai didi

java - 使对象的字段对于数组列表中存储的每个对象都是唯一的

转载 作者:行者123 更新时间:2023-12-01 16:52:47 25 4
gpt4 key购买 nike

所以我有一个存储客户的数组列表,我的任务是制作它,以便没有客户可以拥有相同的 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);
}

最佳答案

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

因此,每次运行代码时,您都必须从文件中读取所有行,创建一个 Customer 并将其存储在 Set 中。使用 Set 时,当您调用 customerList.add(customer) 时,Set 本身将负责避免添加重复项。Set 使用方法 equalshashCode 来检查 Custom 是否已在 Set 中,因此请务必正确实现这些方法。

关于java - 使对象的字段对于数组列表中存储的每个对象都是唯一的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61657273/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com