About Question enthuware.ocpjp.v7.2.1301 :
Posted: Sat Mar 16, 2013 8:43 pm
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)
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)