Thursday, July 29, 2010

Set: Before.java

Courtesy of SCJP Sun® Certified Programmer for Java™ 6 Study Guide Exam (310-065) (9780071591065)
Chapter 7, Question 3






This program will compile. However, it gives the following warning:



Note: source/tree/b4/Before.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.




When recompiling with -Xlint, the compiler outputs the following:

source/tree/b4/Before.java:7: warning: [unchecked] unchecked call to add(E) as a member of the raw type java.util.Set
set.add("2");
      ^
source/tree/b4/Before.java:8: warning: [unchecked] unchecked call to add(E) as a member of the raw type java.util.Set
set.add(3);
      ^
source/tree/b4/Before.java:9: warning: [unchecked] unchecked call to add(E) as a member of the raw type java.util.Set
set.add("1");
      ^

When this program is run, TreeSet compares the contents of sets, it see that "2" and 3 are two different types and throw a ClassCastException.


Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
    at java.lang.Integer.compareTo(Integer.java:50)
    at java.util.TreeMap.put(TreeMap.java:562)
    at java.util.TreeSet.add(TreeSet.java:255)
    at Before.main(Before.java:7)
 

To create a neater runtime error, implement try/catch block














Now the runtime error will output


Check your code, you did NOT add a String!


To avoid a runtime error implement Generics. This tells the compiler what datatype is allowed in set, as shown in line 5.  















Now when we compile, the following error is generated:

symbol  : method add(int)
location: interface java.util.Set
          set.add(3);
             ^
1 error



To fix this code, change line 7 to set.add("3");, so you are now adding a String instead of an int.

 

No comments:

Post a Comment