← Quiz: Comparable vs Comparator: all 10 questions
Quiz: Comparable vs Comparator · Question 4 of 10
Why is return a.price - b.price; a risky compare method for int prices?
Why is return a.price - b.price; a risky compare method for int prices?
- A.It is too slow
- B.It sorts in reverse
- C.The subtraction can overflow and give the wrong sign
- D.It does not compile
Answer & explanation
Correct answer: The subtraction can overflow and give the wrong sign
With large or negative values, a - b can go past the int range and wrap around. Use Integer.compare.
Can you get the rest right without peeking?
Take the timed Quiz: Comparable vs Comparator quiz free. Pass it to earn XP and count towards your certificate.
Start the quiz →