Leaderboard: Fields and get
Fields and constructor
private T[] arr; // elements stay sorted descending in [0, size)
private int size;
private final int k; // the most elements the board will ever hold
@SuppressWarnings({"unchecked"})
public Leaderboard(int k) {
if (k <= 0) {
throw new IllegalArgumentException("capacity must be positive");
}
this.k = k;
arr = (T[]) new Comparable[k + 1];
size = 0;
}
The cast is the same idiom SortedArray uses, and T extends Comparable<T> is what lets the board rank its elements.
The one new detail is the backing array’s length: , not k. add inserts before it trims, so when a value gets onto a full board, size is briefly , and the insert has to write to index k. A k-length array has no such index. The spare slot is where that element sits between the insert and the trim.
The other new detail is that arr is sorted in descending order. The problem statement already walked through why.
The get operation
Same as what get does in SortedArray.
public T get(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException();
}
return arr[index]; // index 0 is the highest, stored right there
}