Page 1 of 1

About Question enthuware.ocpjp.v7.2.1301 :

Posted: Sat Mar 16, 2013 8:43 pm
by alex
Hi,

StudyGroup mathGroup = new StudyGroup();       
mathGroup.add(new Person("MATH"));       
System.out.println("A");

There are two answers:
1. It will compile without warning but will throw an exception at runtime.
2. It will only print : A

Answer 2 is not correct. Because add method will throw Exception
Exception in thread "main" java.lang.ClassCastException: main.java.Person cannot be cast to java.lang.Comparable
at java.util.TreeMap.compare(TreeMap.java:1188)
at java.util.TreeMap.put(TreeMap.java:531)
at java.util.TreeSet.add(TreeSet.java:255)

If look at the code of TreeMap, they will compare keys beetween each other
public V put(K key, V value) {
Entry<K,V> t = root;
if (t == null) {
compare(key, key); // type (and possibly null) check

So, explanation: "Thus, when you add the first element, since there is nothing to compare this element to, there is no exception. " also is not correct.

Pleach check. (jdk 1.7.0_02)

Re: About Question enthuware.ocpjp.v7.2.1301 :

Posted: Tue Mar 19, 2013 10:40 am
by alex
Hi, any comments?

Re: About Question enthuware.ocpjp.v7.2.1301 :

Posted: Tue Mar 19, 2013 10:43 am
by admin
We are still investigating. Apparently, the behavior changed recently. It used to work as given earlier.

-Paul.

Re: About Question enthuware.ocpjp.v7.2.1301 :

Posted: Tue Mar 19, 2013 11:29 am
by alex
Ok, my apologies.
I thought that you just missed my post.

Alex

Re: About Question enthuware.ocpjp.v7.2.1301 :

Posted: Tue Mar 19, 2013 5:38 pm
by admin
Hi Alex,
In light of how it behaves currently, we have updated the question and the explanation.

thank you for your feedback!
Paul.