在 Guava 中,是否有一种有效的方法来添加或删除项目ImmutableList
(当然,在此过程中创建新列表)。
我能想到的最简单的方法是:
private ImmutableList<String> foos = ImmutableList.of();
public void addFoo(final String foo) {
if (this.foos.isEmpty()) {
foos = ImmutableList.of(foo);
} else {
foos = ImmutableList.<String>builder().addAll(foos).add(foo).build();
}
}
public void removeFoo(final String foo) {
final int index = this.foos.indexOf(foo);
if (index > -1) {
final Builder<String> builder = ImmutableList.<String>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<String> tmpList = Lists.newArrayList(this.foos);
if(tmpList.remove(foo))this.foos=ImmutableList.copyOf(tmpList);
}
但不幸的是,它比我能想到的任何仅 Guava 的方法都简单得多。我错过了什么吗?