ProgrammingHardProduct-company placement · Java
Why is the comparator (a, b) -> a - b unsafe for sorting arbitrary int values in Java?
- A. Subtraction is slower than comparison and may time out
- B. a - b can overflow, giving the wrong sign (e.g. Integer.MIN_VALUE - 1 is positive)
- C. A comparator must return only −1, 0 or 1
- 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
- What is printed? java String s = "ab"; StringBuilder sb = new StringBuilder("ab"); System.out.print(s.equals(sb) + " " +…
- What happens when this class is compiled? java class Code implements Comparable<String>, Comparable<Integer> { public int compareTo(String…
- Which statement about Java anonymous classes is correct?
- Which lines fail to compile? java // Java 10 or later var list = new ArrayList<>(); // L1 list.add(1); list.add("a"); // L2 var x; // L3…
- What happens when this is compiled? java // Java 17 sealed class Shape permits Circle, Square { } final class Circle extends Shape { }…
- What is printed? java class AppEx extends Exception { } class DbEx extends AppEx { } // static method of the main class: static void run()…