可变对象
# 可修改性: 可变对象是指其状态(内部数据)可以被修改或更改。一旦创建,可以在程序的执行过程中对其进行修改。
不可变对象
# 不可修改性: 不可变对象是指一旦创建,其状态就不能被修改或更改。任何修改操作都会返回一个新的对象,而不是在原对象上进行修改。
## 可变对象
public class MutableExample {
public static void main(String[] args) {
// 可变对象示例:ArrayList
List<String> mutableList = new ArrayList<>();
mutableList.add("Apple");
mutableList.add("Banana");
mutableList.add("Cherry");
System.out.println("Original List: " + mutableList);
// 修改对象状态
mutableList.add("Date");
System.out.println("Modified List: " + mutableList);
}
}
## 不可变对象
public final class ImmutableExample {
private final String fruit;
public ImmutableExample(String fruit) {
this.fruit = fruit;
}
public String getFruit() {
return fruit;
}
public ImmutableExample withAdditionalFruit(String additionalFruit) {
// 返回一个新的对象,而不是修改现有对象
return new ImmutableExample(this.fruit + ", " + additionalFruit);
}
public static void main(String[] args) {
// 不可变对象示例
ImmutableExample immutableObj = new ImmutableExample("Apple");
System.out.println("Original Fruit: " + immutableObj.getFruit());
// 修改对象状态,返回新对象
ImmutableExample newImmutableObj = immutableObj.withAdditionalFruit("Banana");
System.out.println("Original Fruit (after modification): " + immutableObj.getFruit());
System.out.println("New Fruit: " + newImmutableObj.getFruit());
}
}