Bug 440377 - [1.8][null] Bogus warning "variable X cannot be null" on Map methods that return @NonNull value type
Summary: [1.8][null] Bogus warning "variable X cannot be null" on Map methods that ret...
Status: CLOSED DUPLICATE of bug 331651
Alias: None
Product: JDT
Classification: Eclipse Project
Component: Core (show other bugs)
Version: 4.4   Edit
Hardware: PC All
: P3 normal (vote)
Target Milestone: ---   Edit
Assignee: JDT-Core-Inbox CLA
QA Contact:
URL:
Whiteboard:
Keywords:
Depends on:
Blocks:
 
Reported: 2014-07-24 13:15 EDT by Sean Van Gorder CLA
Modified: 2014-07-24 14:29 EDT (History)
1 user (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description Sean Van Gorder CLA 2014-07-24 13:15:18 EDT
When null type annotation is used to mark a Map's value type as @NonNull, Eclipse assumes that the return type of Map.remove(Object) includes the @NonNull annotation, and therefore cannot be null. This makes it impossible to check the return value for null (indicating the map did not contain the given key) without generating bogus warnings.

Example:


@NonNullByDefault({})
public class NullTest {
    public static void main(String[] args) {
        Map<Integer, @NonNull String> map = new HashMap<>();
        String val = map.remove("badkey");
        if (val == null) { // WARNING 1
            System.out.println("NULL"); // WARNING 2
        }
    }
}


The above code will generate two bogus warnings:
WARNING 1: Null comparison always yields false: The variable val cannot be null at this location
WARNING 2: Dead code

However, running the code will print "NULL".
Comment 1 Sean Van Gorder CLA 2014-07-24 13:25:09 EDT
Update: This also applies to Map.get(Object), Map.put(K, V), and any other method with return type V that are intended to return null in certain cases.
Comment 2 Stephan Herrmann CLA 2014-07-24 14:29:19 EDT
Thanks for the report.

Please see bug 437881 comment 1.

*** This bug has been marked as a duplicate of bug 331651 ***