【发布时间】:2016-04-19 18:40:59
【问题描述】:
我正在尝试用新的修改版本替换集合中的元素。下面是旨在展示我想要实现的目标的简短代码。
整个想法是我有一个由其他对象的集合组成的对象。在某个时间点,我预计集合中的这个对象(在我的示例手机中)可能需要一些修改,我只想在一个地方修改代码。
我知道为了更新对象的属性,我可以在遍历集合时使用 setter,如下所示。但也许有更好、更通用的方法来实现这一点。
public class Customer {
private int id;
private Collection<Phone> phoneCollection;
public Customer() {
phoneCollection = new ArrayList<>();
}
//getters and setters
}
和电话类
public class Phone {
private int id;
private String number;
private String name;
//getters and setters
}
和
public static void main(String[] args) {
Customer c = new Customer();
c.addPhone(new Phone(1, "12345", "aaa"));
c.addPhone(new Phone(2, "34567", "bbb"));
System.out.println(c);
Phone p = new Phone(2, "9999999", "new name");
Collection<Phone> col = c.getPhoneCollection();
for (Phone phone : col) {
if (phone.getId() == p.getId()) {
// This is working fine
// phone.setNumber(p.getNumber());
// phone.setName(p.getName());
// But I'd like to replace whole object if possible and this is not working, at least not that way
phone = p;
}
}
System.out.println(c);
}
}
这有可能实现我想要的吗? 我尝试了复制构造函数的想法和我在网上找到的其他方法,但它们都没有像我预期的那样工作。
编辑 1
读了一些cmets后,我有了一个想法
我在 Phone 类中添加了以下方法
public static void replace(Phone org, Phone dst){
org.setName(dst.getName());
org.setNumber(dst.getNumber());
}
现在我的 foreach 部分看起来像这样
for (Phone phone : col) {
if (phone.getId() == p.getId()) {
Phone.replace(phone, p);
}
}
它完成了这项工作。 现在,如果我更改 Phone 类属性,我只需要更改该方法。你认为这样解决问题可以吗?
【问题讨论】:
-
不,你不能这样做。如果集合是不可修改的,您希望它如何工作?
-
是的,它不起作用,因为
foreach是一个只读循环,您不能更改对phone的引用
标签: java collections iteration