美文网首页
Set.clear()报UnsupportedOperation

Set.clear()报UnsupportedOperation

作者: 燃灯道童 | 来源:发表于2022-12-16 11:17 被阅读0次

    问题场景
    有个业务场景,一个类别对应多个内容,一起提交。增删改查都是一对多,测试起来也没有问题。
    但是在执行unit test的时候出现UnsupportedOperationException。

    报错图片.png

    业务逻辑
    A entity中有个属性是Set<Bentity>, 更新时先把数据库中查询的Set置空,然后再添加到前端传过来的数据。

    解决方法
    写unit test的时候把所有创建entity的地方抽成了一个类,在生成用到的这个entity的时候,当时写了Set.of()导致的,我新创建Set并重新塞值后就可以了。
    Set.of的代码:

        public static PostgreSQLGiftSetTagEntity createPostgreSQLGiftSetTag(){
            PostgreSQLGiftSetTagEntity postgreSQLGiftSetTagEntity = new PostgreSQLGiftSetTagEntity();
            BeanUtils.copyProperties(createGiftSetTagDTO(),postgreSQLGiftSetTagEntity);
            postgreSQLGiftSetTagEntity.setGiftSetList(Set.of(createPostgreSQLGiftSet()));
            return postgreSQLGiftSetTagEntity;
        }
    

    调整后的代码:

        public static PostgreSQLGiftSetTagEntity createPostgreSQLGiftSetTag(){
            PostgreSQLGiftSetTagEntity postgreSQLGiftSetTagEntity = new PostgreSQLGiftSetTagEntity();
            BeanUtils.copyProperties(createGiftSetTagDTO(),postgreSQLGiftSetTagEntity);
            Set<PostgreSQLGiftSetEntity> postgreSQLGiftSet = new HashSet<>();
            postgreSQLGiftSet.add(createPostgreSQLGiftSet());
            postgreSQLGiftSetTagEntity.setGiftSetList(postgreSQLGiftSet);
            return postgreSQLGiftSetTagEntity;
        }
    

    原因
    报错信息指向的是ImmutableCollections类,这是不可变集合,不可做改变,用add、clear等方法,编辑器虽然不会报错,但是运行的时候报UnsupportedOperationException。

    ImmutableCollections是一种不可变类型,一旦创建就不能改变。
    常见创建不可变集合方式就是List.of("1","2"))或Arrays.asList("1","2"),对其进行值更改的时候就会报UnsupportedOperationException,创建可以变化的集合即可,如上调整后的代码。

    参考链接:
    什么是不可变集合:https://www.h3399.cn/201801/532185.html
    不可变集合的定义与发展:https://mdnice.com/writing/b62b8d6cd6124264ac39f72e4474d208

    相关文章

      网友评论

          本文标题:Set.clear()报UnsupportedOperation

          本文链接:https://www.haomeiwen.com/subject/jxrrqdtx.html