我相信这种情况可以证明以下说法是正确的:
public class Immutable { private final String name; private Date dateOfBirth; public Immutable(String name, Date dateOfBirth) { this.name = name; this.dateOfBirth = dateOfBirth; } public String getName() { return name; } public Date getDateOfBirth() { return dateOfBirth; }}getName()很好,因为它也返回不可变的对象。但是,该
getDateOfBirth()方法可以打破不变性,因为客户端代码可以修改返回的对象,因此也可以修改对象
Immutable:
Immutable imm = new Immutable("John", new Date());imm.getName(); //safeDate dateOfBirth = imm.getDateOfBirth();//hundreds of lines laterdateOfBirth.setTime(0); //we just modified `imm` object返回不可变的对象和基元是安全的(因为它们是通过值返回的)。但是,您需要制作可变对象的防御性副本,例如
Date:
public Date getDateOfBirth() { return new Date(dateOfBirth.getTime());}并将集合包装在不可变的视图中(如果它们是可变的),例如,请参见
Collections.unmodifiableList():
public List<Integer> getSomeIds() { return Collections.unmodifiableList(someIds);}


