OCP Question 24, Explanation

Given:

class MutualFund{
    int capital;
    String name;
    public MutualFund (int capital, String name) {
        this.capital = capital;
        this.name = name;
    }
    public String toString () {
        return capital + ":" + name;
    }
}

and this code fragment:

Set<MutualFund> funds = new TreeSet<>();
funds.add(new MutualFund (293, "Pimco"));
funds.add(new MutualFund (190, "Vanguard"));
System.out.println(funds);

What is the result?

A. 293 Pimco
190 Vanguard
B. 190 Vanguard
293 Pimco
C. A compilation error occurs
D. A ClassCastException is thrown at run time

 

The correct answer is D.

 

A TreeSetA TreeSET, you say?! This one is sorted by definition, which means MutualFund must implement Comparable otherwise TreeSet would have no idea how to sort its elements, that is, MutualFund objects. Let’s fix the problem:

class MutualFund implements Comparable<MutualFund>{
    int capital;
    String name;
    public int compareTo(MutualFund mf){
        return mf.capital - this.capital;  // sorting descending
    }
    public MutualFund (int capital, String name) {
        this.capital = capital;
        this.name = name;
    }
    public String toString () {
        return capital + ":" + name;
    }
}

Run the Test class now and observe the output: [293:Pimco, 190:Vanguard]. See how inattentive were the creators of the question? But is it a good idea to be guided by these minor typos to correct conclusions? Personally, I wouldn’t rely on them, it’s not the OCA exam where everything was much, much simpler…

Leave Comment

Your email address will not be published. Required fields are marked *