【发布时间】:2016-10-11 14:00:11
【问题描述】:
我有一个平面文件阅读器类,它从 dat 文件中读取数据,创建存储在其唯一数组列表中的人员、客户和产品对象,我必须将其用于 getInvoice 方法。从发票 dat 文件输入新属性时,我只为我从发票 dat 文件中读取的产品创建一个新的产品列表。这似乎工作正常,但是每个发票对象上的某些产品属性正在更改。
当使用产品数组列表作为字段实例化新发票对象时,是否会创建对添加到下面代码中的产品列表的引用,或者创建该列表后的副本?如果它只是一个参考,为什么当我阅读每个发票对象中的产品列表时,每张发票的产品对象数量是正确的(而不是所有产品)?此外,如果我在创建发票对象(将产品列表作为字段)后清除新产品数组列表,那么我所有发票中的产品列表都是空的。为什么是这样?如果 arraylist 不起作用,我还能怎么做?谢谢,如果需要,我可以添加更多代码。
public ArrayList<Invoice> getInvoices() {
readPersons();
readCustomers();
readProducts();
Scanner sc = null;
try {
sc = new Scanner(new File("data/Invoices.dat"));
sc.nextLine();
while (sc.hasNextLine()) {
ArrayList<Product> product = new ArrayList<Product>();
String line = sc.nextLine();
String data[] = line.split(";");
String invoiceCode = data[0].trim();
String customerCode = data[1].trim();
Customer customer = null;
for(Customer aCustomer: customerList) {
if (customerCode.equals(aCustomer.getCustomerCode())) {
customer = aCustomer;
break;
}
}
String personCode = data[2].trim();
Person person = null;
for(Person aPerson: personList) {
if (personCode.equals(aPerson.getPersonCode())) {
person = aPerson;
break;
}
}
String invoiceDate = data[3];
String products[] = data[4].split(",");
for (int i = 0; i < products.length; i++) {
String productData[] = products[i].split(":");
for(Product aProduct: productList) {
if (aProduct.getProductCode().equals(productData[0])) {
aProduct.setInvoiceDate(this.getDateTime(invoiceDate));
if (productData.length == 1) {
aProduct.setQuantity(1);
product.add(aProduct);
} else if (productData.length == 2) {
aProduct.setQuantity(Integer.parseInt(productData[1]));
product.add(aProduct);
} else if (productData.length == 3) {
aProduct.setQuantity(Integer.parseInt(productData[1]));
for(Product anotherProduct: product) {
if (anotherProduct.getProductCode() == productData[2]) {
aProduct.setParkingPassCount(anotherProduct.getQuantity());
break;
}
}
product.add(aProduct);
}
break;
}
}
}
// Creates an Invoice object
Invoice invoice = new Invoice(invoiceCode, invoiceDate, customer, person, product);
// Adds the Invoice object into Invoice ArrayList
invoiceList.add(invoice);
}
sc.close();
return invoiceList;
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
}
public DateTime getDateTime(String Date){
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd");
DateTime dateTime = formatter.parseDateTime(Date);
return dateTime;
}
【问题讨论】:
-
不,它没有,它使用您告诉他使用的参考。如果您指的是已经存在的产品并更改了该产品的某些值,这在逻辑上也会反映到存在该确切实例的其他集合的更改中,因为它是相同的。 (但目前还不清楚您要做什么以及您在哪里遇到问题)