JDK-5074427 : Foreach seeing wrong parameterized return type
  • Type: Bug
  • Component: tools
  • Sub-Component: javac
  • Affected Version: 5.0
  • Priority: P3
  • Status: Closed
  • Resolution: Not an Issue
  • OS: windows_xp
  • CPU: x86
  • Submitted: 2004-07-15
  • Updated: 2004-07-15
  • Resolved: 2004-07-15
Related Reports
Relates :  
Description

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) 
======================================================================

Comments
EVALUATION Not a bug, the declaration of b makes it raw: Base b = new Child(); Please change it to: Base<String> b = new Child(); ###@###.### 2004-07-15
15-07-2004