Back to questions
JuniorTheoryCommon
What does the program print?
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
P[] ps = {new P("A", 2), new P("C", 1), new P("B", 3)};
Arrays.sort(ps);
for (P p : ps) { System.out.print(p.name()); }
}
}
record P(String name, int age) implements Comparable<P> {
public int compareTo(P o) { return Integer.compare(age, o.age); }
}CAB
- Expecting the names in alphabetical order:
Arrays.sortandCollections.sortfollowcompareTo, and here it comparesage, so the youngest comes first. - Expecting the oldest first:
compareToreturns a negative number whenthisgoes first, andInteger.compare(age, o.age)is negative for a smaller age.
- How do you change
compareToto sort from the oldest to the youngest? - What happens if
Pdoes not implementComparableand you callArrays.sort?