Community
Participate
Working Groups
Build Identifier: 20100218-1602 Enhanced for loops do not implement type safety checks on array initializers, e.g. HashSet<String> x = new HashSet<String>(); x.add("a"); HashSet<Integer> y = new HashSet<Integer>(); y.add(1); // The following gives no warning for (Set<String> refSet : new Set[] { x, y }) { for (String str : refSet) System.out.println(str); } Gives a Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String Reproducible: Always Steps to Reproduce: As above
PS of course it's impossible to create a generic Set<String>[] array, so that warning should be given if attempted, and a normal type safety warning for new Set[] as shown in the listing.
Complete test case: import java.util.HashSet; import java.util.Set; public class Snippet { void foo() { HashSet<String> x = new HashSet<String>(); x.add("a"); HashSet<Integer> y = new HashSet<Integer>(); y.add(1); Set<String> OK= new Set[] { x, y }; // The following gives no warning for (Set<String> BUG : new Set[] { x, y }) { for (String str : BUG) System.out.println(str); } } }
(In reply to comment #2) > Complete test case: Thanks Dani. There was a minor typo, the test should be: import java.util.HashSet; import java.util.Set; public class Snippet { void foo() { HashSet<String> x = new HashSet<String>(); x.add("a"); HashSet<Integer> y = new HashSet<Integer>(); y.add(1); Set<String> [] OK= new Set[] { x, y }; // <<------ OK is an array. // The following gives no warning for (Set<String> BUG : new Set[] { x, y }) { for (String str : BUG) System.out.println(str); } } }
>There was a minor typo, the test should be: Strange - I thought I just copied and pasted the example. Mmh.
Created attachment 175742 [details] Patch under consideration
All tests pass. Satyam, please review, TIA.
(In reply to comment #6) Srikanth, Patch look good.
Released in HEAD for 3.7 M2.
Verified for 3.7M2 using build I20100909-1700.