【问题标题】:how to remove an item from a UnmodifiableList in a protobuf如何从 protobuf 中的 UnmodifiableList 中删除项目
【发布时间】:2016-09-27 10:08:34
【问题描述】:

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

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

我试图删除一个项目 i 并在同一位置添加另一个项目 i

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

    categoryList.remove(i);

但我得到一个不受支持的错误

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

如何进行替换?

【问题讨论】:

  • 你的categoryList是从数组转换过来的吗?
  • 列表 categoryList = builder.getCategoryList();
  • 我想知道builder.getCategoryList()里面是通过数组还是列表工作的?
  • @EladBenda 检查我的答案。希望对你有帮助!

标签: java list protocol-buffers proto


【解决方案1】:

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

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

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

【讨论】:

  • 这仅限于一个类是否有可能我们可以创建所有子类也是可变的。这样我们就可以将任何内部类对象更新到任何级别的内部类?
【解决方案2】:

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

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

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

【讨论】:

    【解决方案3】:

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

    /*Example*/
    String[] strArray = {"a","b","c","d"};
    
    List<String> strList = Arrays.asList(strArray);
    
    strList.remove(0); // throw exception
    

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

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

    add()remove() 无法完成。

    【讨论】:

      【解决方案4】:

      如果你想更新 protobuff builder 列表,你可以这样实现:

            //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.
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-19
        • 1970-01-01
        • 2013-05-01
        • 2017-02-14
        • 2019-05-01
        • 2019-05-29
        • 2017-07-21
        相关资源
        最近更新 更多