Problem 4 (List.of())

Let's create a list of MutableMelon via List.of():

private final MutableMelon melon1 
= new MutableMelon("Crenshaw", 2000);
private final MutableMelon melon2
= new MutableMelon("Gac", 1200);

private final List<MutableMelon> list = List.of(melon1, melon2);

So, is the list unmodifiable or immutable? The answer is unmodifiable. While mutator methods will throw UnsupportedOperationException, the hardcoded instances can still be accessed via the List.get() method. Once they can be accessed, they can be mutated:

MutableMelon melon1l = list.get(0);
MutableMelon melon2l = list.get(1);

melon1l.setWeight(0);
melon2l.setWeight(0);

Now, the list will reveal the following melons (so the list was mutated):

Crenshaw(0g), Gac(0g)

For the next examples, let's consider the following immutable class:

public final class ImmutableMelon {

private final String type;
private final int weight;

// constructor, getters, equals() and hashCode() omitted for brevity
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.176.228