Java Bug: Final List or Map Not Truly Immutable

❗ Java Bug: Why final List or final Map Is Not Immutable in Java Recently, I ran into immunity issue in Java, which I've never paid attention before. It’s a common misconception that marking a field final automatically makes it “safe” or “immutable.” Unfortunately, this is not true when the field holds a mutable object such as a List or Map. Let’s look at this Java class: @Getter @Builder public class Plan { private final List<String> toDoList; } At first glance, this looks immutable: the field is final, and there is no setter. But watch what happens: List<String> initialToDoList = new ArrayList<>(Arrays.asList("Buy groceries", "Read a book", "Exercise")); var plan = Plan.builder().toDoList(initialToDoList).build(); List<String> firstList = plan.getToDoList(); firstList.size()==3; firstList .add("Learn Java"); //No Exception Obtain list again AFTER adding the item: List<String> secondList = plan.getToDoList(); Now firstList.size()==4 and secondList.size()==4 firstList contains the newly added item 'Learn Java' secondList contains the newly added item 'Learn Java' ❇️ Conclusion: Summary object looks immutable from the outside, but its internal state can be changed at any time. That’s not immutability—that’s an illusion of immutability. I feel it's a Java Bug. If it's final, why not just make it immutable no matter if it's a collection or not 😂. #Java

To view or add a comment, sign in

Explore content categories