Can someone explain me what I'm doing wrong or is it the class which isn't immutable?
Question: Which of these classes is/are immutable?
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 7, 6]
C. Both classes
D. Neither class
Explanation in the book:
14. B. An immutable class must not allow the state to change. In the Flower class, the caller has a reference to the List being passed in and can change the size or elements in it. Similarly, any
Class with a reference to the object can get the List by calling get() and make these changes. The Flower class is not immutable. The Plant class shows how to fix these problems
and is immutable. Option B is correct.
Why is the class Plant not immutable? In my Test class, I wanted to see, if the class Plant is immutable. But the class Plant isn't immutable, it is mutable! I can change the values and add() a new value!
Why? Have I made a wrong example? I know an ArrayList and a List is mutable, is that the problem?
Can someone fix my example to make the class Plant immutable? Should I have to return a Collections.unmodifiableList()?
Thanks for some help.