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

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
Viper

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

Post 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"...

admin
Site Admin
Posts: 10398
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

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

Post 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.

Viper

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

Post 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.

devlam
Posts: 50
Joined: Sun Nov 10, 2013 4:39 am
Contact:

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

Post 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?

admin
Site Admin
Posts: 10398
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

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

Post 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);
    }
    
}

Post Reply

Who is online

Users browsing this forum: No registered users and 6 guests