0

Here's a simple class that does not use raw types, and it seems to me it should not compile, but it does:

import java.util.HashMap; import java.util.Map;

public final class MapBug {
  public static void main(String[] args) {
    Map<Integer, MapBug> integerMap = makeMap();
    String txt = "Bad key -- wrong type!";
    MapBug mapBug = integerMap.get(txt); // <-- No compiler error here?
  }

  private static Map<Integer, MapBug> makeMap() { return new HashMap<>(); }
}

Usually when I see this kind of problem, it's because the user is using raw types, but this code doesn't do that. The map is declared with Integer as its key type, and I'm clearly passing in a String. As far as I can remember, this used to produce compiler errors. What am I missing?

(I'm compiling with Java 1.8.0_31. I can't upgrade on my current system, but this wrong type should have produced a compiler bug way back in Java 1.5.)

MiguelMunoz
  • 4,548
  • 3
  • 34
  • 51

2 Answers2

0

If you look at the reference: https://docs.oracle.com/javase/8/docs/api/java/util/Map.html

get takes Object

shikhanshu
  • 1,466
  • 2
  • 16
  • 32
0

Check the docs: The Map.get() method takes an Object - if you try to us a key of the wrong type, it just returns null:

It's a bit of a pain, but presumably it works this way because the Map interface predates generics.

hugh
  • 2,237
  • 1
  • 12
  • 25
  • Okay, I get it. That's very annoying. I want a type-safe get() method. It was apparently done this way for backwards compatibility when they generified the class, but I would appreciate a truly type-safe map get() method. – MiguelMunoz Jul 18 '18 at 19:29
  • @MiguelMunoz https://www.youtube.com/watch?v=7knIi3LGf4M – JB Nizet Jul 18 '18 at 19:40
  • 1
    @MiguelMunoz Use IntelliJ, and you'll have a warning telling you that a Mapmay not contain objects of type String. – JB Nizet Jul 18 '18 at 19:43
  • Yep, me too. Way too many times I've missed a conversion on my keys and only realised when I've debugged the code. – hugh Jul 21 '18 at 07:59