修改列表不应影响其对象-Java

问题描述 投票:0回答:2

我上了蝴蝶课:

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;
}

}

还有一个给我问题的JUnit测试用例:

@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()));    
}   

我的问题是:如果修改颜色本身,如何防止更改Butterfly对象的颜色。我尝试使用List.of,List.copyOf,Collections.unmodifiableList,但似乎无法弄清楚。任何帮助将不胜感激。预先谢谢!

java list immutability
2个回答
2
投票

更改行

this.colors = colors;

to

this.colors = List.copyOf(colors);

这将使Butterfly.colors字段成为传递到构造函数中的List的不可修改的副本。

如果您希望Butterfly可以通过其他方式进行修改,则可以在构造函数中进行可变复制,但也必须在“ getter”中进行复制。

this.colors = ArrayList<>(colors);

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

(从技术上讲,ArrayList构造函数可以被击败,但是您通常不必为此担心。)


0
投票

更改Butterfly类的getColors()方法:

public List<String> getColors() {
    return colors == null ? null : new ArrayList<>(colors);
}
© www.soinside.com 2019 - 2024. All rights reserved.