Page 1 of 1
About Question enthuware.ocpjp.v11.2.1862 :
Posted: Wed Feb 02, 2022 6:59 pm
by fawcette01
What is going on here?
The list will not be printed, only the object references. Or should we assume there is a toString()?
Re: About Question enthuware.ocpjp.v11.2.1862 :
Posted: Thu Feb 03, 2022 1:30 am
by admin
There is no need to assume. All objects have a toString method already. It may not print the value of the fields of the object, but it does print a unique string for that object (No, it doesn't print object reference. It prints
the hashcode).
Further, what the code actually prints is not really relevant here because all it says is that the list is printed, which it does. It doesn't claim anything about the actual format or content of what is printed.
Re: About Question enthuware.ocpjp.v11.2.1862 :
Posted: Thu Aug 04, 2022 10:27 am
by mansi29feb
The book class is not implementing Comparable interface then how the compareTo function is working on line //1
Re: About Question enthuware.ocpjp.v11.2.1862 :
Posted: Thu Aug 04, 2022 10:59 am
by admin
Book doesn't implement Comparable. But the code passes a Comparator instance that is able to compare two Book objects.
This Comparator uses the compareTo method of String class.
Observe the lambda used to create the Comparator. It calls b1.getGenre().compareTo and not b1.compareTo.
Re: About Question enthuware.ocpjp.v11.2.1862 :
Posted: Thu Aug 04, 2022 11:24 am
by mansi29feb
Thanks for the explaination. Got it.
Re: About Question enthuware.ocpjp.v11.2.1862 :
Posted: Wed Sep 03, 2025 3:34 pm
by nnavlani
Comparator is supposed to use compare and NOT compareTo, then why is the option "Code will fail to compile because of code at //1." NOT the correct answer ?
Re: About Question enthuware.ocpjp.v11.2.1862 :
Posted: Wed Sep 03, 2025 8:52 pm
by admin
Why I think it should fail compilation?
The given lambda expression correctly provides an implementation of the compare method.
Re: About Question enthuware.ocpjp.v11.2.1862 :
Posted: Thu Sep 04, 2025 1:00 pm
by nnavlani
But the method called in the Comparator is compareTo, and not compare? So does it mean that the Comparator Book has a wrong call there to compareTo just to confuse us?
Re: About Question enthuware.ocpjp.v11.2.1862 :
Posted: Thu Sep 04, 2025 9:21 pm
by admin
Not sure what is causing the confusion. Comparator is an interface, it doesn't call anything. It has a method named compare, and the code in the compare method is free to implement the logic required for comparison as it deems fit. In this case, the code in the compare method utilizes the compareTo method, which is already available in String.
Logically, there is no difference between Comparator and Comparable and no difference between their methods compare and compareTo. Comparator compares two given objects, while Comparable compares "this" object with another given object.