Some Eclipse Foundation services are deprecated, or will be soon. Please ensure you've read this important communication.

Bug 358209

Summary: Warning when Map.get() is called with the wrong type
Product: [Eclipse Project] JDT Reporter: Ben Davis <entheh>
Component: CoreAssignee: Stephan Herrmann <stephan.herrmann>
Status: VERIFIED DUPLICATE QA Contact:
Severity: enhancement    
Priority: P3 CC: manoj.palat, markus.kell.r, stephan.herrmann
Version: 3.7   
Target Milestone: 4.5 M6   
Hardware: PC   
OS: Windows 7   
Whiteboard:

Description Ben Davis CLA 2011-09-20 05:51:58 EDT
Build Identifier: 20110615-0604

Map.get(), Map.remove(), Set.contains(), and many similar functions take 'Object' even if the collection is parameterised with a more specific key. I understand there's a reason for this, but I rarely want to pass any other type to these functions, so I would find it useful if Eclipse could warn me when I do it accidentally.

There are two cases: passing a potentially compatible type (where casting would be valid), and passing an incompatible type (where casting wouldn't be valid). These could be separate warnings if you like.

Reproducible: Always

Steps to Reproduce:
Example code that I'd like to see warnings for:

class C {}
interface I {}

void method(
    HashMap<C,Object> map,
    C compatibleKey,
    Object potentiallyCompatibleKey1,
    I potentiallyCompatibleKey2,
    String incompatibleKey
) {
    Object o;
    o=map.get(compatibleKey);
    o=map.get(potentiallyCompatibleKey1);  //"potentially incompatible key" warning
    o=map.get(potentiallyCompatibleKey2);  //"potentially incompatible key" warning
    o=map.get(incompatibleKey);  //"incompatible key" warning
}

Obviously there are more methods to think about than just HashMap.get; and there are cases involving wildcards that would need some thought; but even if this is just implemented for non-wildcard keys, that would cover most of the cases I encounter in my code :)

Thanks in advance!
Comment 1 Markus Keller CLA 2013-06-11 09:07:41 EDT

*** This bug has been marked as a duplicate of bug 410218 ***
Comment 2 Manoj N Palat CLA 2015-03-17 02:59:33 EDT
Verified for Eclipse Mars 4.5 M6 Build id: I20150316-2000