Problem 3 (Collections.unmodifiableList() and static block)

Let's create a list of MutableMelon via the Collections.unmodifiableList() method and a static block:

private static final List<MutableMelon> list;
static {
final MutableMelon melon1 = new MutableMelon("Crenshaw", 2000);
final MutableMelon melon2 = new MutableMelon("Gac", 1200);

list = Collections.unmodifiableList(Arrays.asList(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)
..................Content has been hidden....................

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