ProgrammingHardProduct-company placement · Java

Why is the comparator (a, b) -> a - b unsafe for sorting arbitrary int values in Java?

  1. A. Subtraction is slower than comparison and may time out
  2. B. a - b can overflow, giving the wrong sign (e.g. Integer.MIN_VALUE - 1 is positive)
  3. C. A comparator must return only −1, 0 or 1
  4. D. Lambdas cannot be used as Comparators for boxed Integers

Correct answer: B. a - b can overflow, giving the wrong sign (e.g. Integer.MIN_VALUE - 1 is positive)

Comparator only needs the sign to be right, but int subtraction wraps around on overflow, so very negative minus positive can come out positive. Integer.compare(a, b) avoids this.

More OOP with C++ and Java questions

Exams that ask this topic