导致异常的代码

    @DeleteMapping("delete")
    public Result delete(@RequestBody Long[] ids){
        try {
            List<Long> list = Arrays.asList(ids);
            list.forEach(id->{
                recurveIdList(id,list);
            });
            service.removeByIds(list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result().err();
        }
        return new Result().ok();
    }

   public void recurveIdList(Long id,List<Long> ids){
//        List<CadPart> list1 = service.list(new QueryWrapper<CadPart>().in("parent_id",ids));
        List<CadRelation> cadRelations = relationService.list(new QueryWrapper<CadRelation>().eq("parent_id", id));
        if(CollectionUtils.isNotEmpty(cadRelations)){
            List<Long> list = cadRelations.stream().map(CadRelation::getPartId).collect(Collectors.toList());
            ids.addAll(list);
            cadRelations.forEach(item->{
                recurveIdList(item.getPartId(),list);
            });
//            recurveIdList(list);
        }
    }

报错如下

image.png

报错原因

调用Arrays.asList()产生的List中add、remove方法时报异常,这是由于Arrays.asList()返回的是Arrays的内部类ArrayList, 而不是java.util.ArrayList。Arrays的内部类ArrayList和java.util.ArrayList都是继承AbstractList,remove、add等方法在AbstractList中是默认throw UnsupportedOperationException而且不作任何操作。java.util.ArrayList重写这些方法而Arrays的内部类ArrayList没有重写,所以会抛出异常。需要用新的list转换一下

解决办法

public Result delete(@RequestBody Long[] ids){ try { List<Long> list = Arrays.asList(ids); List<Long> idList= new ArrayList<>(list ); idList.forEach(id->{ recurveIdList(id,list); }); service.removeByIds(list); } catch (Exception e) { e.printStackTrace(); return new Result().err(); } return new Result().ok(); }