Problem 2 (Arrays.asList())

Let's create a list of MutableMelon by hardcoding the instances directly in Arrays.asList():

private final List<MutableMelon> list 
= Collections.unmodifiableList(Arrays.asList(
new MutableMelon("Crenshaw", 2000),
new MutableMelon("Gac", 1200)));

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

MutableMelon melon1 = list.get(0);
MutableMelon melon2 = list.get(1);

melon1.setWeight(0);
melon2.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
18.218.93.169