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

Inference does not work in enhanced for loop

XMLWordPrintable

    • Fix Understood
    • generic, x86
    • generic, linux

      I'm wondering if the below code is buggy:

      import java.util.*;

      public class Test {
          static <K,V> Iterable<Map.Entry<K,V>> getEntries() {return null;}

          public static void main(String[] args) {
              for (Map.Entry<?,Integer> e : getEntries()) {
              }
          }
      }


      The compiler reports the following error:

      Test.java:7: incompatible types
      found : java.util.Map.Entry<java.lang.Object,java.lang.Object>
      required: java.util.Map.Entry<?,java.lang.Integer>
                      for (Map.Entry<?,Integer> e : getEntries()) {
                                                              ^

      Why isn't the enhanced for loop expression used as a context for applying the
      type inference algorithm? Is this a bug or am I expected to explicitly provide an instantiation for
      all method parameters?

      At first, it seemed that the problem was related to the enhanced for loop expression; so I tried
      The following workaround (whichdoesn't compile either):

      public class Test {
          static <K,V> Iterable<Map.Entry<K,V>> getEntries() {return null;}

          public static void main(String[] args) {
              Iterable<Map.Entry<?,Integer>> it = getEntries(); //should be a workaround
              for (Map.Entry<?,Integer> e : it) {
              }
          }
      }

      But, surprisingly, I found that this code (surprisingly) compiles:

      public class Test {
          static <K,V> Iterable<Map.Entry<K,V>> getEntries() {return null;}

          public static void main(String[] args) {
              Iterable<Map.Entry<String,Integer>> it = getEntries(); //should be a workaround
              for (Map.Entry<?,Integer> e : it) {
              }
          }
      }

      In other words it seems that the inference process only works with concrete types but not with wildcard types.
      Is this problem due to a bug in the inference process?

            abuckley Alex Buckley
            ahe Peter Ahe
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Created:
              Updated:
              Imported:
              Indexed: