首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >修改列表不应影响其对象- Java

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

Stack Overflow用户
提问于 2020-02-23 04:45:57
回答 2查看 74关注 0票数 0

我有一个类Butterfly:

代码语言:javascript
复制
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测试用例,它给我带来了问题:

代码语言:javascript
复制
@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,但我似乎就是想不通。任何帮助都将不胜感激。提前谢谢你!

EN

回答 2

Stack Overflow用户

发布于 2020-02-23 04:48:56

更改线路

代码语言:javascript
复制
this.colors = colors;

代码语言:javascript
复制
this.colors = List.copyOf(colors);

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

如果你希望Butterfly在其他方面是可修改的,你可以在构造函数中创建一个可变的副本,但你也必须在"getter“中进行复制。

代码语言:javascript
复制
this.colors = ArrayList<>(colors);

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

(从技术上讲,ArrayList构造函数可能会被击败,但您通常不必担心这一点。)

票数 3
EN

Stack Overflow用户

发布于 2020-02-23 04:49:51

更改蝶类的getColors()方法:

代码语言:javascript
复制
public List<String> getColors() {
    return colors == null ? null : new ArrayList<>(colors);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60356635

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档