Skip to content

Instantly share code, notes, and snippets.

@digitalex
Created August 8, 2012 14:22
Show Gist options
  • Save digitalex/3295420 to your computer and use it in GitHub Desktop.
Save digitalex/3295420 to your computer and use it in GitHub Desktop.
TopList
class TopList<E extends Comparable> {
@Delegate
private List items
private int maxSize
private Comparator<E> comparator = new ReverseComparator()
TopList(int maxSize) {
this.maxSize = maxSize
this.items = new ArrayList(maxSize)
}
boolean add(E item) {
insertInOrder(item)
trimToSize()
true
}
private def insertInOrder(E item) {
int index = Collections.binarySearch(items, item, comparator)
int insertionPoint = index < 0 ? Math.abs(index + 1) : index
items.add(insertionPoint, item)
}
private void trimToSize() {
while (items.size() > maxSize) {
items.remove(items.size()-1)
}
}
// Reverses the comparison to make the order descending
class ReverseComparator implements Comparator<E> {
int compare(E a, E b) {
b.compareTo(a)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment