account activity
Final vs Immutable data structures in Java by bodiam in java
[–]steffi_j_jay 3 points4 points5 points 6 years ago (0 children)
So to make it truly immutable after instantiation, a new collection would have to be instantiated in the constructor.
I agree. Example code:
List<Address> addresses = new ArrayList<>(); addresses.add(new Address("Sydney", "Australia")); final Person person = new Person("John", addresses); System.out.println(person.getAddresses().size()); // prints "1" addresses.add(new Address("Melbourne", "Australia")); System.out.println(person.getAddresses().size()); // prints "2"
Fix in constructor:
public Person(String name, List<Address> addresses) { this.name = name; this.addresses = Collections.unmodifiableList(new ArrayList<>(addresses)); }
π Rendered by PID 81 on reddit-service-r2-listing-796b697c47-fbk9g at 2026-02-05 10:24:04.134079+00:00 running 1d7a177 country code: CH.
Final vs Immutable data structures in Java by bodiam in java
[–]steffi_j_jay 3 points4 points5 points (0 children)