Typesafe effectively read only java collections?

184 Views Asked by At

I'm searching for a java library for collections with no methods that allow for mutations. effectively immutable read only collections.

By that I mean, NO METHODS. Not like the usual Java immutable collections that have methods like add or remove that throw an exception when called. No... I want the compiler to let me know I'm trying to do something not allowed, instead of some error at runtime.

I know it exists because I've used it, but I cannot remember the name of such library.

2

There are 2 best solutions below

5
On BEST ANSWER

Eclipse Collections: https://www.eclipse.org/collections/

Their own guide on immutable collections says:

All of the basic containers in Eclipse Collections have interfaces for both mutable and immutable (unchangeable) forms. This departs somewhat from the JCF model, in which most containers are mutable.

An immutable collection is just that - once created, it can never be modified, retaining the same internal references and data throughout its lifespan. An immutable collection is equal to a corresponding mutable collection with the same contents; a MutableList and an ImmutableList can be equal.

2
On

Guava's immutable collections declare mutable methods using @Deprecated so their use will emit a compiler warning.

This is probably the best of both worlds, since it allows passing an ImmutableCollection wherever a Collection is expected.