• Post Reply Bookmark Topic Watch Topic
  • New Topic

bad using method get()  RSS feed

 
manu chaox
Ranch Hand
Posts: 110
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

e.g.:

I have

HashMap cars = new HashMap<Integer, Car>();

and if I will make mistake and try this

... = cars.get(SomeObject);// it should be cars.get(someInteger);

then IDE(eclipse) don't report any error.

How can I handle this problem ?

Thanks
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66306
152
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
manu chaox
Ranch Hand
Posts: 110
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, but i afraid this doesn't solve the problem.
Same behaviaor.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Unfortunately, the get() method of interface Map is not type-safe with regard to the key. If you look in the API documentation, you'll see that the method takes an Object, and not the type of the key (which is Integer in your example). This is most likely so because it needed to be backwards compatible with Java 1.4 and older, which didn't have generics.

So, there is no way to make it produce a compiler error if you pass anything else than an object of the key type to the get() method.
 
manu chaox
Ranch Hand
Posts: 110
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot.
And is there any possibility check this by IDE(eclipse) or is it only thing of a programmer ?
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't know if there's a way you can make Eclipse check for this particular case.

You might be interested in a tool like FindBugs - that's a very good tool that does static analysis on your source code, which can find hundreds of different kinds of bugs and potential problems in your source code. Maybe there's a check for something like this in FindBugs. Note that there's an Eclipse plug-in for FindBugs, so that you can integrate it nicely into Eclipse.
 
Campbell Ritchie
Marshal
Posts: 56546
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I tried it, with get(new Object()); and with get("Campbell");

Needless to say, I got null twice. Obviously the get() method accepts any Object of any type as a key; it is safe since it returns null. If you passed an Integer outwith the domain of the Map, you would get null anyway. So this method doesn't require type-checking to be safe to use.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!