Java 中 [String](String.md) 类型变量是**不可变的**,意思就是 JVM 那块区域被写了数据以后就变成只读的了,不会再覆写了 ![image.png|1000](https://imagehosting4picgo.oss-cn-beijing.aliyuncs.com/imagehosting/fix-dir%2Fpicgo%2Fpicgo-clipboard-images%2F2024%2F08%2F17%2F00-37-21-b765d03110c9116f466fcac5ce745e40-202408170037139-93a835.png) ## case 那我这段代码有问题吗? ```java // 遍历每一天 boolean needRebuild = false; ShortDate currentDay = fromDate; while (currentDay.isBefore(toDate)) { // 当天命中才会进入过滤打标 if (hitStrategies.get(currentDay) != null) { if (markingAbnormalPriceAtDay(currentDay, fromDate, hitStrategies.get(currentDay), physicalPriceMap, cWrappers)) { needRebuild = true; } } currentDay.addDays(1); } return needRebuild; } ``` 有问题。主要问题在于 `currentDay.addDays(1)` 这行代码的使用方式。 问题在于 `addDays()` 方法返回一个新的 ShortDate 对象,而不是修改当前对象。你当前的代码没有接收这个返回值,所以 `currentDay` 实际上并没有被更新,这会导致死循环。 让我们修复这段代码: ```java // 遍历每一天 boolean needRebuild = false; ShortDate currentDay = fromDate; while (currentDay.isBefore(toDate)) { // 当天命中才会进入过滤打标 if (hitStrategies.get(currentDay) != null) { if (markingAbnormalPriceAtDay(currentDay, fromDate, hitStrategies.get(currentDay), physicalPriceMap, cWrappers)) { needRebuild = true; } } // 修复:需要接收addDays的返回值 currentDay = currentDay.addDays(1); } return needRebuild; ``` 主要修改是: - 将 `currentDay.addDays(1)` 改为 `currentDay = currentDay.addDays(1)` 这是因为 ShortDate 是不可变类(immutable),类似于 String 类,它的方法不会修改原对象,而是返回一个新对象。所以需要接收这个返回值并更新 currentDay 变量,否则循环中的 currentDay 永远不会改变,导致死循环。 --- [值传递](值传递.md) [引用传递](引用传递) ```java public static void main(String[] args) { ProductRoom p = new ProductRoom(); p.setBedType(BedTypeNew.BIG); HomogenizedProduct h = new HomogenizedProduct(p); h.setBedType(BedTypeNew.DOUBLE); System.out.println(p.getBedType()); public HomogenizedProduct(ProductRoom productRoom) { if (productRoom == null) { return; } this.physicalRoomId = productRoom.getPhysicalRoomId(); this.physicalRoomName = productRoom.getPhysicalRoomName(); this.breakfast = productRoom.getBreakfast(); this.payment = productRoom.getPayment(); this.customizeCancelType = productRoom.getCustomizeCancelType(); this.sellUnit = productRoom.getSellUnit(); this.bedType = productRoom.getBedType(); }```