简体   繁体   中英

Modifying a list should not affect its object - Java

I have a class Butterfly:

public class Butterfly extends Insect {

/**
 * Field to hold the list of colors that a butterfly object is.
 */
private List<String> colors;

/**
 * Constructor to initialize the fields.
 * 
 * @param species - Species of Butterfly.
 */
public Butterfly(String species, List<String> colors) {
    super(species);
    this.colors = colors;
}

/**
 * Constructor to initialize an existing Butterfly object.
 * 
 * @param butterfly - Butterfly object
 */
public Butterfly(Butterfly butterfly) {
    this(butterfly.getSpecies(), butterfly.getColors());
}

/**
 * Getter for the colors of the butterfly. 
 * 
 * @return the colors - Colors of the butterfly.
 */
public List<String> getColors() {
    return colors;
}

@Override
public String toString() {
    return getSpecies() + " " + colors;
}

}

And a JUnit test case that is giving me issues:

@Test
void butterfly_immutable() {
    List<String> colors = new ArrayList<>();
    Collections.addAll(colors, "orange", "black", "white");

    Butterfly b1 = new Butterfly("Monarch", colors);
    Butterfly b2 = new Butterfly(b1);

    // Modifying the original color list should not affect b1 or b2.
    colors.set(0, "pink");

    // Modifying the colors returned by the getters should not affect b1 or b2
    List<String> b1Colors = b1.getColors();
    b1Colors.set(1, "lime");
    List<String> b2Colors = b2.getColors();
    b2Colors.set(1, "cyan");

    assertTrue(sameColors(List.of("orange", "black", "white"), b1.getColors()));    
    assertTrue(sameColors(List.of("orange", "black", "white"), b2.getColors()));    
}   

My question is: how do I prevent changing the colors of the Butterfly object if the colors themselves are modified. I have attempted using List.of, List.copyOf, Collections.unmodifiableList, and I just cannot seem to figure this out. Any help would be greatly appreciated. Thank you in advance!

Change the line

this.colors = colors;

to

this.colors = List.copyOf(colors);

This will make a the Butterfly.colors field an unmodifiable copy of the List passed into the constructor.

If you wanted Butterfly to be modifiable in other ways, you could make a mutable copy in the constructor, but you would also have to copy in the "getter".

this.colors = ArrayList<>(colors);

public List<String> getColors() {
    return List.copyOf(colors);
}

(Technically the ArrayList constructor can be defeated, but you shouldn't usually have to worry about that.)

Change getColors() method of Butterfly class:

public List<String> getColors() {
    return colors == null ? null : new ArrayList<>(colors);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM