Skip to content

Tag: immutability

Immutable class while using a cache

While going through JCIP, I came across the below code snippet which was considered as Immutable. However the explanation provided makes me confused. OneValueCache wouldn’t be immutable without the copyOf calls in the constructor and getter. Arrays.copyOf was added as a convenience in Java 6; clone would also work. Aren’t the state vars of OneValueCache themselves Immutable with final and

Make immutable Java object

My goal is to make a Java object immutable. I have a class Student. I coded it in the following way to achieve immutability: public final class Student { private String name; private String age; …

Immutable Type: public final fields vs. getter

I need a small Container-Class for storing some Strings which should be immutable. As String itself is an immutable type, I thought of something like that: Many people seem to object using public fields at all and use Getters instead. IMHO this would be just boilerplate in this case, because String itself is immutable. Other thoughts I may be missing

Immutable array in Java

Is there an immutable alternative to the primitive arrays in Java? Making a primitive array final doesn’t actually prevent one from doing something like I want the elements of the array to be unchangeable. Answer Not with primitive arrays. You’ll need to use a List or some other data structure: