1

Why doesn't this Java code generate any compiler error?

Map<String, String> m = new HashMap<String, String>();
m.get(1);

I try to find an Integer in a map which maps Strings to Strings. This is clearly a programming mistake.

Similarly, this code does not generate an error either:

Map<Integer, String> m = new HashMap<Integer, String>();
m.get("dd1");

So Java compiler does not seem to check the type of the argument to Map.get(Object) method. Any ideas?

Cagin Uludamar
  • 372
  • 1
  • 3
  • 16
  • Also take a look at http://stackoverflow.com/questions/857420/what-are-the-reasons-why-map-getobject-key-is-not-fully-generic – René Link Dec 03 '13 at 07:38
  • "This is clearly a programming mistake." No it is not. Objects of one class can be equal to objects of another class. It happens to not be the case for `Integer` and `String`, but it can happen in general. – newacct Dec 04 '13 at 11:07

6 Answers6

4

Java compiler does not seem to check the type of the argument to Map.get(Object) method.

Certainly it does. It checks that it's an Object. There's nothing else for it to check. The only way there can be an 'invalid class' is if you are using a primitive type.

user207421
  • 305,947
  • 44
  • 307
  • 483
3

Map interface get method takes Object as a argument.

No error in both the cases. The only thing is it must be an Object and if the equals method satisfied with passed Object, then the value returns.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
2

m.get(Object); argument here is valid for any object type in your map. So that will not give you compile error.

Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
0

Generally it check at the time of insertion. in put method.

when no wrong data inserted in map then not required to check while getting data using get method

shreyansh jogi
  • 2,082
  • 12
  • 20
0

As you can see in the documentation of (Java-Map) the get method does not use the generic injection, but instead Object as input parameter. So you will get a ClassCastException at Runtime. This differs from the put method where the generic type injection is used.

flex36
  • 146
  • 1
  • 3
  • "So you will get a ClassCastException at Runtime." No you won't. It can't. Read the contract of the `get` method. – newacct Dec 04 '13 at 11:08
-1

it will check your put action and the return value( public V get(Object key) ), not all of the action.