forked from Archives/Athou_commafeed
rewrote with a backing arraylist
This commit is contained in:
@@ -1,51 +1,44 @@
|
||||
package com.commafeed.backend;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.PriorityQueue;
|
||||
|
||||
import com.google.common.collect.Iterables;
|
||||
import com.google.common.collect.Lists;
|
||||
public class FixedSizeSortedSet<E> {
|
||||
|
||||
public class FixedSizeSortedSet<E> extends PriorityQueue<E> {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
private List<E> inner;
|
||||
|
||||
private final Comparator<? super E> comparator;
|
||||
private final int capacity;
|
||||
|
||||
public FixedSizeSortedSet(int capacity, Comparator<? super E> comparator) {
|
||||
super(Math.max(1, capacity), comparator);
|
||||
this.inner = new ArrayList<E>(Math.max(0, capacity));
|
||||
this.capacity = capacity < 0 ? Integer.MAX_VALUE : capacity;
|
||||
this.comparator = comparator;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean add(E e) {
|
||||
public void add(E e) {
|
||||
int position = Math.abs(Collections.binarySearch(inner, e, comparator) + 1);
|
||||
if (isFull()) {
|
||||
E last = last();
|
||||
int comparison = comparator.compare(e, last);
|
||||
if (comparison < 0) {
|
||||
remove(last);
|
||||
return super.add(e);
|
||||
} else {
|
||||
return false;
|
||||
if (position < inner.size()) {
|
||||
inner.remove(inner.size() - 1);
|
||||
inner.add(position, e);
|
||||
}
|
||||
} else {
|
||||
return super.add(e);
|
||||
inner.add(position, e);
|
||||
}
|
||||
}
|
||||
|
||||
public E last() {
|
||||
return Iterables.getLast(this);
|
||||
return inner.get(inner.size() - 1);
|
||||
}
|
||||
|
||||
public boolean isFull() {
|
||||
return size() == capacity;
|
||||
return inner.size() == capacity;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public List<E> asList() {
|
||||
return (List<E>) Lists.newArrayList(toArray());
|
||||
return inner;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user