列表对象的死存储 - 如何解决?

Dead store to List object - how to solve?

在下面第 5 行,Sonar 代码分析显示问题 "Dead store to eventList in",如何通过我的代码解决这个问题?

Sonar 代码分析说: 该指令为局部变量赋值,但该值未在任何后续指令中读取或使用。通常,这表明存在错误,因为从未使用过计算出的值。 请注意,Sun 的 javac 编译器通常会为最终局部变量生成死存储。因为 SpotBugs 是一个基于字节码的工具,所以没有简单的方法来消除这些误报。


@GetMapping(path = Constants.GET_REPORT, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Map> getReport(@PathVariable(required = false) String keyword) {
        HashMap<Object, Object> sitesMap = new LinkedHashMap<>(); 
        try {
            List<EventV1> myList = new ArrayList<EventV1>();  // <<------------problem here  (Dead store to myList in..)
            if (keyword != null && !keyword.equalsIgnoreCase("null")) {// search of the keyword
                myList = eventService.getBySearch(keyword);
            } else {
                myList = eventService.getSomething();
            }
            if (myList != null && myList.size() > 0) {
                LOGGER.info("-size of the all events" + myList.size());
                sitesMap.put(Constants.SUCCESS, true);
                sitesMap.put(Constants.SIZE, myList.size());
                sitesMap.put("mylist", myList); 
                return new ResponseEntity<Map>(sitesMap, HttpStatus.OK);
            } else {
                sitesMap.put(Constants.SUCCESS, false);
                sitesMap.put("size", 0);
                sitesMap.put("mylist", null); 
                return new ResponseEntity<Map>(sitesMap, HttpStatus.NO_CONTENT);
            }
        } catch (Exception exc) { 
            throw new ResponseStatusException(HttpStatus.EXPECTATION_FAILED, REGISTER_FAIL_MSG, exc);
        }
    }

这是因为您创建了不必要的 ArrayList 对象。只需替换:

List<EventV1> myList = new ArrayList<EventV1>();
                       ^^^^^^^^^^^^^^^^^^^^^^^^
if (keyword != null && !keyword.equalsIgnoreCase("null")) {
    myList = eventService.getBySearch(keyword);
} else {
    myList = eventService.getSomething();
}

List<EventV1> myList;

if (keyword != null && !keyword.equalsIgnoreCase("null")) {
    myList = eventService.getBySearch(keyword);
} else {
    myList = eventService.getSomething();
}

您可以在声明期间将 myList 赋值给 null。将它分配给 new ArrayList<EventV1>() 是没有用的,因为它无论如何都会从方法调用中获取结果:eventService.getBySearch(keyword)eventService.getSomething()。您基本上为 new ArrayList<EventV1>() 分配了一些内存,但立即取消引用它,从而浪费了一些宝贵的内存。