我想更新Contact对象,该对象有2个字段-名称和电话号码。 不幸的是,我不知道为什么setter方法不起作用。
首先,我尝试使用#1
版本的updateContact()方法-以下代码。
我认为它可能与更新对象的引用有关,而不是与对象本身有关?我不确定。
如果有人可以向我解释,为什么使用setter的代码不起作用...-我的意思是它会更新函数中的“联系人”,但不会更新ArrayList中的“联系人”。
#2
方法有效,但是我不确定这是否是个好主意/解决方案-嗯,它有效...但是我认为对于setter来说,它也应该有效。
public void updateContact(String name) {
Contact contact = findContact(name);
System.out.print("Enter new name: ");
contact.setName(scanner.nextLine());
System.out.print("Enter new phone number (9 numbers): ");
contact.setPhoneNumber(scanner.nextLine());
}
public void updateContact(String name) {
Contact contact = findContact(name);
String replaceName;
String replaceNumber;
System.out.print("Enter new name: ");
replaceName = scanner.nextLine();
System.out.print("Enter new phone number (9 numbers): ");
replaceNumber = scanner.nextLine();
Contact replace = new Contact(replaceName, replaceNumber);
contacts.set(contacts.indexOf(contact), replace);
}
findContact方法
public Contact findContact(String name) {
Contact currentContact = null;
for (Contact contact : contacts) {
if (contact.getName().equals(name)) {
currentContact = new Contact(name, contact.getPhoneNumber());
}
}
return currentContact;
}
谢谢您的帮助。
答案 0 :(得分:2)
您的findContact()方法不会返回对ArrayList中的Contact对象的引用,而是要创建一个具有数据副本的新对象,然后将其返回。
按如下所示更改它,您的第一种方法应该起作用:
95