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

Foreach seeing wrong parameterized return type

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Not an Issue
    • Icon: P3 P3
    • None
    • 5.0
    • tools
    • x86
    • windows_xp



      Name: jl125535 Date: 07/15/2004


      FULL PRODUCT VERSION :
      java version "1.5.0-beta3"
      Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0-beta3-b57)
      Java HotSpot(TM) Client VM (build 1.5.0-beta3-b57, mixed mode, sharing)

      ADDITIONAL OS VERSION INFORMATION :
      Microsoft Windows XP [Version 5.1.2600]

      A DESCRIPTION OF THE PROBLEM :
      The code segment included will compile correctly only if the base class does not accept a generic type. If a generic type is added to the base class, the compiler reports an error on the return method.


      ERROR MESSAGES/STACK TRACES THAT OCCUR :
      H:\Bud\Desktop>javac -source 1.5 -target 1.5 -Xlint Base.java
      Base.java:12: incompatible types
      found : java.lang.Object
      required: java.lang.String
            for(String str : b.getParams().keySet()) {
                                                 ^
      1 error

      REPRODUCIBILITY :
      This bug can be reproduced always.

      ---------- BEGIN SOURCE ----------
      import java.util.*;

      public abstract class Base<E> {
         public abstract Map<String, String> getParams();
      }

      class Child extends Base<String> {

         public static void main(String[] args) {
            Base b = new Child();

            for(String str : b.getParams().keySet()) {
               System.out.println(str + " " + b.getParams().get(str));
            }

         }

         private Map<String, String> map;

         public Child() {
            map = new HashMap<String, String>();
            map.put("Hello", "World");
         }

         public Map<String, String> getParams() {
            return map;
         }

      }

      ---------- END SOURCE ----------

      CUSTOMER SUBMITTED WORKAROUND :
      Save the returned set from keySet() to a variable, then use the variable in the for loop. This will cause a warning to be produced when compiling with -Xlint:

      javac -source 1.5 -target 1.5 -Xlint Base.java
      Base.java:12: warning: [unchecked] unchecked conversion
      found : java.util.Set
      required: java.util.Set<java.lang.String>
            Set<String> set = b.getParams().keySet();
                                                  ^
      1 warning
      (Incident Review ID: 285795)
      ======================================================================

            ahe Peter Ahe
            jleesunw Jon Lee (Inactive)
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved:
              Imported:
              Indexed: