RTFJD (the JavaDocs are your friends!) If you haven't read them in a long time, then RRTFJD (they might have changed!)
There is nothing tricky about Comparators. It is object ordering that is tricky.Jesse Silverman wrote:. . . the very tricky subject of Comparator. . . .
But it doesn't. Look what happened when I tried that Comparator on JShell:-The ints comparator uses natural sort order. . . .
You will find some of the pitfalls about ordering in the Java™ Tutorials. That link explains how straight subtraction and negation of the result can both go wrong.My JShell wrote:jshell> Comparator<Integer> ints = (i1, i2) -> i1 -i2;
ints ==> $Lambda$26/0x0000000800ba5450@3d646c37
jshell> ints.compare(2_000_000_000, -2_000_000_000)
$6 ==> -294967296
jshell> ints.compare(5, 3)
$7 ==> 2
You should be using Comparators for any type with more than one possible criterion for ordering. If your type has only one possible criterion for ordering, then make the type implement Comparable. A tree can fail to operate correctly if it has to deal with a type whose compareTo() method isn't “consistent with equals()”.Two common ways that Comparator is used . . .
If whatever appears on the left is “larger” than whatever appears on the right, you get a positive result. The built‑in sorting methods always sort in ascending order full stop. If you want to sort descending, you will have to pass a Comparator or similar making 3 bigger than 4. Example:-Afraid I don't know any straightforward mnemonics.. . . "This is a positive number that means the first number is bigger and we are sorting in ascending order" . . . "I want to sort in ascending order, are you positive I need to swap these two elements?" . . .
Or simply remember which is bigger and trust the collection's implementation to sort it for you.. . . "Am I positive that the new element should be placed to the right of the node I am looking at?" . . .
Have you tried it? Have you seen what type is returned from Map#values()? It is most unlikely to be a List.. . . values() explicitly returns a Collection (probably a List but I think not officially specified) . . .
The real exam may contain questions requiring such knowledge of the methods in the API.Question 7 . . . posit[s] a mythical .valueSet() . . . to trick us.
[OCP 21 book] | [OCP 17 book] | [OCP 11 book] | [OCA 8 book] [OCP 8 book] [Practice tests book] [Blog] [JavaRanch FAQ] [How To Ask Questions] [Book Promos]
Other Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, TOGAF part 1 and part 2
Consider Paul's rocket mass heater. |