0

Having the simple following java code:

Map<Integer,String> map = new HashMap<>();
//map.put("sd","A");
map.put(2,"B");
map.remove(2);
map.remove("A");

I can put only Integer keys (thus commented line cause a compile time error) but I can remove any class Keys (thus last line is valid). Type is checked in put() but not in remove().

Why Map.put method uses the key parameter type and remove method does not?

Wouldn't be helpful the compiler to inform, as it does in put(), that I use Integers as type for keys thus there is no mean trying to remove String keys?

Ilias Stavrakis
  • 753
  • 10
  • 19

1 Answers1

2

This is because of backward compatibility with old Java versions (Java 1.4 and older), which did not yet have generics.

In old Java versions, the remove method on Map (as well as other methods) took a parameter of type Object. Sun / Oracle could not change this to remove(T obj) when Java 5 came out, because that would have broken backward compatibility - old source code might not have compiled anymore without changes on the newer Java version.

Oracle is always extremely careful to keep things backward compatible when a new Java version comes out.

Jesper
  • 202,709
  • 46
  • 318
  • 350