Page 1 of 1

About Question com.enthuware.ets.scjp.v6.2.86 :

Posted: Sun Jan 27, 2013 10:10 am
by Viper
Program prints that one of the correct answers is "It will only print : A", but it isn't correct in my case. I have tried to compile the code with javac 1.6.0_35, and I have had the runtinme exception immediately ("A" hasn't been printed) :

Code: Select all

Exception in thread "main" java.lang.ClassCastException: Person cannot be cast to java.lang.Comparable
        at java.util.TreeMap.compare(Unknown Source)
        at java.util.TreeMap.put(Unknown Source)
        at java.util.TreeSet.add(Unknown Source)
        at StudyGroup.add(StudyGroup.java:16)
        at StudyGroup.main(StudyGroup.java:21)
Line 21 in main is "mathGroup.add(new Person("MATH"));" just before printing "A" line, so ClassCastException is throwing before program can chance of printing "A"...

Re: About Question com.enthuware.ets.scjp.v6.2.86 :

Posted: Sun Jan 27, 2013 10:33 am
by admin
Are you sure you are running the code exactly as given in the question? I just tried it and it works as explained. It prints A and then throws the exception.

HTH,
Paul.

Re: About Question com.enthuware.ets.scjp.v6.2.86 :

Posted: Sun Jan 27, 2013 11:10 am
by Viper
You are right. I have run the program under java 1.7. It looks that, the "A" is printed at java 1.6 and it isn't printed at java 1.7.

Re: About Question com.enthuware.ets.scjp.v6.2.86 :

Posted: Sun Feb 09, 2014 4:21 am
by devlam
In the explanation is says "But if their compareTo() method does not work with both the types, you cannot add both type of elements in the same TreeSet".
Can you explain in more detail. How to make a comparaTo for class A and one for Class B which work for both types?

Re: About Question com.enthuware.ets.scjp.v6.2.86 :

Posted: Sun Feb 09, 2014 5:18 am
by admin
The following are trivial but valid classes with compatible compareTo implementations. Objects of both the classes can be stored in a TreeSet.

Code: Select all

class A1 implements Comparable
{

    @Override
    public int compareTo(Object o) {
        return this.toString().compareTo(""+o);
    }
    
}
class B1 implements Comparable{

    @Override
    public int compareTo(Object o) {
        return this.toString().compareTo(""+o);
    }
    
}