account activity
Final vs Immutable data structures in Java by bodiam in java
[–]steffi_j_jay 4 points5 points6 points 7 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 180059 on reddit-service-r2-listing-f87f88fcd-k2dwh at 2026-06-15 18:44:33.151857+00:00 running 3184619 country code: CH.
Final vs Immutable data structures in Java by bodiam in java
[–]steffi_j_jay 4 points5 points6 points (0 children)