在Guava中,是否有一种有效的方法来添加或删除ImmutableList的项目(当然,在此过程中创建新的列表).
我能想出的最简单的方法是:
private ImmutableList foos = ImmutableList.of();
public void addFoo(final String foo) {
if (this.foos.isEmpty()) {
foos = ImmutableList.of(foo);
} else {
foos = ImmutableList.builder().addAll(foos).add(foo).build();
}
}
public void removeFoo(final String foo) {
final int index = this.foos.indexOf(foo);
if (index > -1) {
final Builder builder = ImmutableList.builder();
if (index > 0) builder.addAll(this.foos.subList(0, index));
final int size = this.foos.size();
if (index < size - 1) builder.addAll(this.foos.subList(index+1, size));
this.foos = builder.build();
}
}
我想避免的是这样的:
public void removeFoo(final String foo) {
final ArrayList tmpList = Lists.newArrayList(this.foos);
if(tmpList.remove(foo))this.foos=ImmutableList.copyOf(tmpList);
}
但不幸的是,它比任何只有番石榴的方法要简单得多.我错过了什么吗?