Which of these classes is/are immutable?
public final class Shape { private final String name; private final List<Integer> counts; public Shape(String name, List<Integer> counts) { this.name = name; this.counts = counts; } /*from ww w.jav a 2 s .com*/ public String getName() { return name; } public List<Integer> getCounts() { return counts; } } public final class Rectangle { private final String name; private final List<Integer> counts; public Rectangle(String name, List<Integer> counts) { this.name = name; this.counts = new ArrayList<>(counts); } public String getName() { return name; } public List<Integer> getCounts() { return new ArrayList<>(counts); } }
B.
An immutable class must not allow the state to change.
In the Shape class, the caller has a reference to the List being passed in and can change the size or elements in it.
Any class with a reference to the object can get the List by calling get()
and make these changes.
The Shape class is not immutable.
The Rectangle class shows how to fix these problems and is immutable.
Option B is correct.