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