Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8339528

No compilation error reported for incorrect Type Checking for Map.get() with Wrapper/Custom Types

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Not an Issue
    • Icon: P4 P4
    • None
    • 8, 11, 17, 21, 23, 24
    • tools
    • generic
    • generic

      ADDITIONAL SYSTEM INFORMATION :
      Any System / OS / JRE

      A DESCRIPTION OF THE PROBLEM :
      The current behaviour of the Map.get() method in Java permits the use of a wrapper type (e.g., Boolean, Integer) but lacks type checking when attempting to retrieve data with any type of key, regardless of the type specified in the generics diamond operator. This effectively breaches type safety validations and introduces unnecessary performance overhead by calculating hash codes and performing equality checks even when their primary types do not correspond.

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      1) Create a Map with a wrapper type as the key type (e.g., Map<Boolean, Integer>).
      2) Attempt to retrieve a value from the map using any other type as the key (e.g.: myMap.get(7)).

             Map<Boolean, Integer> numbersMap = new HashMap<>();
             numbersMap.get(7); //compiles fine
             numbersMap.get(new RandomObject()); // compiles fine

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      The code should result in a compilation error, indicating a type mismatch between the provided key and the declared key type of the map.
      ACTUAL -
      The code compiles without errors and returns 'NULL' but this behaviour undermines the type safety guarantees provided by Java generics, allowing mismatched types to interact without compile-time errors. This could also result in unnecessary boxing and unboxing, as well as inefficient key comparisons and could potentially create performance bottlenecks in large maps.

      ---------- BEGIN SOURCE ----------
      import java.util.Map;
      import java.util.HashMap;

      public class Workshop {
          public static void main(String[] args) {

              Map < Boolean, Integer > numbersMap = new HashMap < > ();
              numbersMap.get(7);
              numbersMap.get(new RandomObject());
          }
      }

      class RandomObject {

      }
      ---------- END SOURCE ----------

            Unassigned Unassigned
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved: