我有一个类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;
}
}和一个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,但我似乎就是想不通。任何帮助都将不胜感激。提前谢谢你!
发布于 2020-02-23 04:48:56
更改线路
this.colors = colors;至
this.colors = List.copyOf(colors);这将使Butterfly.colors字段成为传入构造函数的List的不可修改副本。
如果你希望Butterfly在其他方面是可修改的,你可以在构造函数中创建一个可变的副本,但你也必须在"getter“中进行复制。
this.colors = ArrayList<>(colors);
public List<String> getColors() {
return List.copyOf(colors);
}(从技术上讲,ArrayList构造函数可能会被击败,但您通常不必担心这一点。)
发布于 2020-02-23 04:49:51
更改蝶类的getColors()方法:
public List<String> getColors() {
return colors == null ? null : new ArrayList<>(colors);
}https://stackoverflow.com/questions/60356635
复制相似问题