我正在尝试读取一个文件,其中每一行都用于创建一个我称为Food
的对象。每行也是逗号分隔的,所以我使用 StringTokenizer
类的实例来解析数据。这是我正在使用的文件内容的峰值:
Aldi's Distribution Center,Gertrude ,Hagge,90411,3158,fruit & grapefruit,decay,15,cases,8422,40914
Campbell Soup Company,Roch,Carter,90410,8583,soup & tomato,short-dated,2,pallets,,
Kikkoman Foods,Arnold,Brown,90328,5045,marinade - herb garlic,damaged,4,cases,,
Food
类有几个实例变量,其中一个是我定义的另一个名为 Name
的类。 Name
只有两个实例变量,一个字符串表示名字,另一个表示姓氏。出于某种原因,我最初认为在我的 Name
类中创建一个执行以下操作的函数会很有用:
public Name copy(){
Name nameCopy = new Name(this.first, this.last);
return nameCopy;
}
然后,在创建 Food
类时,我为 Name
创建了以下 get
方法:
public Name getContact(){
return contact.copy();
}
Food
的默认构造函数和重载构造函数如下:
public Food(){
this("Google", new Name(), "091024", "8502", "Jiffy peanut butter", "other", 4399, "cases");
}
public Food(String corpName, Name contact, String date, String productCode, String description, String reason, int number, String cop){
this.corpName = corpName;
this.contact = contact;
this.date = date;
this.productCode = productCode;
this.description = description;
this.reason = reason;
this.number = number;
this.cop = cop;
}
因此,我将 Name
的默认构造函数作为 Food
的默认构造函数的一部分。
下面是我要解决的问题。我用来解析数据的代码如下:
try{
Scanner scan = new Scanner (new File("foodBankInput.txt"));
while(scan.hasNextLine()){
String stringRead = scan.nextLine();
StringTokenizer tokens = new StringTokenizer(stringRead,",");
Food temp = new Food();
temp.setCorpName(tokens.nextToken());
temp.getContact().setLast(tokens.nextToken());
temp.getContact().setFirst(tokens.nextToken());
temp.setDate(tokens.nextToken());
temp.setProductCode(tokens.nextToken());
temp.setDescription(tokens.nextToken());
temp.setReason(tokens.nextToken());
String numberString = tokens.nextToken();
int number = Integer.parseInt(numberString);
temp.setNumber(number);
temp.setCoP(tokens.nextToken());
list.insert((Food)temp);
System.out.println(temp.toString() + "\n");
}
scan.close();
}
list
是我创建的名为 FoodArrayList
的类的一个实例,它几乎执行与 ArrayList
类相同的操作。我现在的问题是,如果我保持 getContact()
不变,我数组中的每个 Food
实例都使用 Name
的默认构造函数。为什么要这样做?我知道每次使用 copy()
时,它都会创建一个 Name
对象的多个副本/实例。但是,根据我定义的 copy()
?
我明白,如果我将 getContact()
方法调整为以下内容,我的代码将按我希望的方式工作:
public Name getContact(){
return contact;
}
但是,我仍然不完全理解为什么这是解决方案。如有任何意见,我们将不胜感激。
最佳答案
这是因为您使用默认构造函数 Food() 创建 temp,它还将一个联系人分配给从默认构造函数 Name() 创建的对象。
接下来您尝试使用 setter 覆盖这些值,但是当您调用 getContact() 时它会返回一个副本。您没有更改与 temp 关联的对象!
修改 getContact() 后,您开始返回与 temp 实例关联的实例。
关于java - 对象引用 - 为什么引用了错误的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34258020/