DEV Community

Discussion on: Make an Immutable Object - in Java

Collapse
 
test1975 profile image
Test

If you are using Java 10 or later, you can make defensive copies of collections using functions like List.copyOf and Map.copyOf.

They make a copy which is inherently immutable. The beauty is, if the collection you are copying is already immutable, it will usually just return a reference to itself instead of making another (needless) copy.

I've been using the immutable collection classes in Google's Guava library to do the same thing for years.

docs.oracle.com/javase/10/docs/api...

google.github.io/guava/releases/sn...

Collapse
 
monknomo profile image
Gunnar Gissel • Edited

Haven’t really played with 10 yet - that sounds really handy!

Love Guava, but I like to see how far I can get without including libraries. Guava is the library that I wish was built in 😍