Java Trivia

Do these compile?

int x = 1;

int class = 1;

int goto = 1;

int static = 1;

int var = 1;

int void = 1;

int const = 1;

Solution

int x = 1;          // Yes...

int class = 1;      // No, java keyword

int goto = 1;       // No, java keyword that is not actually used (reserved)

int static = 1;     // No, java keyword

int var = 1;        // Yes! Reserved type name, not a keyword!

int void = 1;       // No, java keyword

int const = 1;      // No, another reserved java keyword

var var = "var";    // Yes!

Comparison Method Violates its General Contract!

Does this work?

List<Integer> numbers = List.of(1, 3);
Comparator<Integer> comparator = (a,b) -> a - b;
numbers.sort(comparator);

No!

  • Example

    • a := large positive

    • b := large negative

  • (a - b) overflows, creating a negative number

  • Since a - b is negative, comparator thinks a < b

Does this work??

List<Integer> numbers = ...
Comparator<Integer> comparator = (a,b) -> a < b
    ? -1
    : a == b ? 0 : 1;
numbers.sort(comparator);

No!

  • Auto-unboxing is the problem!

  • The a == b is performing reference equality

  • So a == b is usually false

    • Unless a and b are the same object

Does this work???

List<Double> numbers = ...
Comparator<Double> comparator = (a,b) -> a < b
    ? -1
    : a > b ? 1 : 0

No!

  • Example:

    • a := NaN

    • b := any number

  • Any comparison with NaN evaluates to false

NaN < 1000 -> false
NaN > 1000 -> false
NaN == 1000 -> false

…​does this work????

List<Integer> numbers = ...
numbers.sort(Integer::compare);

Yes!

  • Lesson: Just use Integer::compare

Conclusion

Hope you learned something!