0

I found a curious SCJP question that at first looks as if it was answered correctly:

TreeSet<Integer> s = new TreeSet<Integer>();
TreeSet<Integer> subs = new TreeSet<Integer>();
for(int i = 606; i < 613; i++)
    if(i%2 == 0) s.add(i);
subs = (TreeSet)s.subSet(606,true, 630,true); 
s.add(629); 
s.add(630); 
System.out.println(s + " " + subs);

I shared the opinion with the others that this would print [606, 608, 610, 612, 629, 630] [606, 630]. I tried compiling it and to my surprise found out that the code gives a compile error with a warning:

__[unchecked] unckecked conversion__
found: java.util.TreeSet
required: java.util.TreeSet(java.lang.Integer) 

It does compile if I cast the s.subset like this:

subs = (TreeSet<Integer>)s.subSet(606,true, 630,true); 

I found various examples similar to this on the net and no one says that this code doesn't compile. I am confused regarding the correct answer here

I'm compiling it with the compiler 1.6 > so it shouldn't be compiler version issue

EDIT: The short answer is YES, IT COMPILES and long one is: read the accepted answer :)

luigi7up
  • 5,779
  • 2
  • 48
  • 58
  • Why are you surprised that the raw cast gives a compiler warning? – Louis Wasserman Feb 05 '13 at 18:40
  • I had no idea that compiler checks possible casting issues for you... To my knowledge, compiler was playing dumb when you cast: http://stackoverflow.com/questions/10388136/java-casting-resulting-in-run-time-error-instead-of-compilation-error as you can see in this discussion compiler can see that you're trying something stupid, but doesn't warn you... – luigi7up Feb 06 '13 at 09:38

1 Answers1

0

It is not the compile time error. It is indeed the warning message that came because you compiled your code in this way
javac -Xlint:unchecked MyTreeSet.java

where , MyTreeSet.java is the name of your java file.

You still will have the class file generated successfully in your working directoy

Vishal K
  • 12,976
  • 2
  • 27
  • 38
  • Oh, thanks... I saw it was a compile warning and guessed that the compilation was failing... I compiled without -Xlint, though... – luigi7up Feb 06 '13 at 09:33