Space Cadet
Space Cadet

Reputation: 403

What is the best way in terms of space efficiency to make a List of objects immutable?

Prompted by the example provided at 37:19 of this talk by Stuart Marks on Java Collections, I was wondering what is the best way to make a List of objects immutable from a space efficiency perspective.

In my example, I have a List of objects that I retrieve from a database:

List<MyObject> myObjects = myRepository.getMyObjectsThatFitCriteria();

To make this List immutable I can think of three ways to do it

  1. Wrap it in Collections.unModifiableList() but this creates another object and the underlying list itself is still modifiable
  2. Stream over the myObjects list and collect it to an unmodifiable list but this might have a performance impact, particularly if the list is large
  3. Use the List.copyOf() static factory method introduced in Java 9 but this creates another copy of the myObjects list, impacting memory and storage.

Upvotes: 1

Views: 164

Answers (2)

WJS
WJS

Reputation: 40044

Wrap it in Collections.unModifiableList() but this creates another object and the underlying list itself is still modifiable.

You still need to create a list so there is no way around that. But you can always reassign to the same list to effectively remove the reference from access.

list = Collections.unModifiableList(list);

The original list internally is simply referred to (thus not copied) for immutable methods like size(). Any other methods that would allow changes are overridden with methods that throw exceptions if they are invoked. So the overhead is minimal.

Note that unless the contained objects are immutable, they are still subject to alteration.

Upvotes: 0

M A
M A

Reputation: 72854

As mentioned by @VGR in the comment, Collections.unmodifiableList will not copy the elements into a new list, but rather wrap it and prevent modifications on it.

If you're using Spring Data JPA for repository support, it's a good idea to leverage its support for streams: https://www.baeldung.com/spring-data-java-8

Streams are a good way to avoid large memory consumption if the list is large. It does not change the source collection and allows lazy consumption.

Upvotes: 2

Related Questions