gpt4 book ai didi

java - 向 Guava ImmutableList 添加和删除项目

转载 作者:太空狗 更新时间:2023-10-29 22:53:44 25 4
gpt4 key购买 nike

在 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 的方法都要简单得多。我错过了什么吗?

最佳答案

你可以通过过滤来移除,它不会创建中间的ArrayList 或构建器,并且只遍历列表一次:

public void removeFoo(final String foo) {
foos = ImmutableList.copyOf(Collections2.filter(foos,
Predicates.not(Predicates.equalTo(foo)));
}

对于添加,我没有看到更好的解决方案。

关于java - 向 Guava ImmutableList 添加和删除项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12937938/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com