javalistclassnullpointerexceptionfindbugs

Message about a redundant nullcheck of list which is known to be null


I need to have an empty list, to which I'll add some objects (that I pick and parse from AWS S3) based on some criterion. The list might remain empty at the end, which is why I'm checking for null before passing this on to the next function.

public String handleRequest(S3Event s3Event, Context context) {    
    List <myClass> allRows = null;

    s3Event.getRecords().stream()
            .map(S3EventNotification.S3EventNotificationRecord::getS3)
            .forEach(s3Entity -> {
                // some code

                myClass v = jsonSerDe.fromJson(line, myClass.class);
                allRows.add(v);

                // some code
                });

    if(allRows!=null){
        putRecordsinKinesis(allRows);
    }
    return null;
}

However, when I'm building my code, I get the following FindBug error, which is failing my build:

Redundant nullcheck of allRows which is known to be null

What would be the best way to work around this without disabling the Findbugs?


Solution

  • You do have allRows.add(v); but indeed allRows = new ArrayList<>(); is missing, and as allRows is effectively final, it must be done at the declaration. And even then the if is superfluous. So FindBugs is and will be right.


    Also a version with Collectors.toList().

        List <myClass> allRows = s3Event.getRecords().stream()
                .map(S3EventNotification.S3EventNotificationRecord::getS3)
                .map(s3Entity -> {
                    // some code
    
                    myClass v = jsonSerDe.fromJson(line, Vendor.class);
    
                    // some code
                    return v;
                    })
                .collect(Collectors.toList());
    
        if (!allRows.isEmpty()) {
            putRecordsinKinesis(allRows);
        }