如何从 protobuf 中的 UnmodifiableList 中删除一个项目

how to remove an item from a UnmodifiableList in a protobuf

我有一个 protobuf,其中有一个列表作为其成员之一

我想替换此列表中的项目。

我尝试删除一项 i 并在同一位置添加另一项 i

List<Venues.Category> categoryList = builder.getCategoryList();

    categoryList.remove(i);

但是我收到一个不支持的错误

java.lang.UnsupportedOperationException
    at java.util.Collections$UnmodifiableList.remove(Collections.java:1317)

如何进行替换?

其中一个解决方案是创建一个新的可修改列表来包装旧列表——我的意思是将它传递给例如的构造函数新 ArrayList():

List<T> modifiable = new ArrayList<T>(unmodifiable);

从现在开始,您应该可以删除和添加元素了。

我最终克隆了列表,修改了克隆列表并将其替换为旧列表。

List<Venues.Category> clone = categoryList.stream().collect(Collectors.toList());
                clone.remove(i);
                clone.add(i, modifyCategory(category, countryAbbr, gasStationConfig));

                builder.clearCategory();
                builder.addAllCategory(clone);

如果你的列表来自数组,它会抛出 java.lang.UnsupportedOperationException.

/*Example*/
String[] strArray = {"a","b","c","d"};

List<String> strList = Arrays.asList(strArray);

strList.remove(0); // throw exception

因为原始数组和列表是链接的。

列表的大小是固定大小,更改会影响两者。

add()remove() 无法完成。

如果你想更新 protobuf 构建器列表,你可以用这个来实现:

      //Considering builder is your Category list builder.
    List<Venues.Category> categoryList = builder.getCategoryList(); // Previous list.

        builder.setCategory(1, categoryBuilder.build()); //categoryBuilder is your object builder which you want to replace at first location.
// Hope you will get setCategory function by protobuffer, or something like that. because it's created by protobuffer compilation.

        List<Venues.Category> updatedCategoryList = builder.getCategoryList();
    //Your updated list with new object replaced at 1.