Created
August 8, 2012 14:22
-
-
Save digitalex/3295420 to your computer and use it in GitHub Desktop.
TopList
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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