package com.commafeed.backend;

import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;

import org.apache.commons.collections.CollectionUtils;

import com.google.common.collect.Lists;

public class FixedSizeSortedSet<E> extends TreeSet<E> {

	private static final long serialVersionUID = 1L;

	private final Comparator<? super E> comparator;
	private final int maxSize;

	public FixedSizeSortedSet(int maxSize, Comparator<? super E> comparator) {
		super(comparator);
		this.maxSize = maxSize;
		this.comparator = comparator;
	}

	@Override
	public boolean add(E e) {
		if (isFull()) {
			E last = last();
			int comparison = comparator.compare(e, last);
			if (comparison < 0) {
				remove(last);
				return super.add(e);
			} else {
				return false;
			}
		} else {
			return super.add(e);
		}
	}

	@Override
	public boolean addAll(Collection<? extends E> c) {
		if (CollectionUtils.isEmpty(c)) {
			return false;
		}

		boolean success = true;
		for (E e : c) {
			success &= add(e);
		}
		return success;
	}
	
	public boolean isFull() {
		return size() == maxSize;
	}

	@SuppressWarnings("unchecked")
	public List<E> asList() {
		return (List<E>) Lists.newArrayList(toArray());
	}
}
@@ -31,38 +31,8 @@
 %0D%0A%0D%0A
-import java.util.Collection;%0D%0A
 impo
@@ -98,23 +98,29 @@
 va.util.
-TreeSet
+PriorityQueue
 ;%0D%0A%0D%0Aimp
@@ -127,25 +127,25 @@
 ort 
-org.apach
+com.googl
 e.common
 s.co
@@ -144,17 +144,16 @@
 mmon
-s
 .collect
 ions
@@ -152,31 +152,19 @@
 lect
-ions.CollectionUtils;%0D%0A
+.Iterables;
 %0D%0Aim
@@ -251,15 +251,21 @@
 nds 
-TreeSet
+PriorityQueue
 %3CE%3E 
@@ -488,16 +488,25 @@
 %09%09super(
+maxSize, 
 comparat
@@ -869,232 +869,66 @@
 %0A%0D%0A%09
-@Override%0D%0A%09public boolean addAll(Collection%3C? extends E%3E c) %7B%0D%0A%09%09if (CollectionUtils.isEmpty(c)
+public E last(
 ) %7B%0D%0A%09%09
-%09
 return 
-false;%0D%0A%09%09%7D%0D%0A%0D%0A%09%09boolean success = true;%0D%0A%09%09for (E e : c) %7B%0D%0A%09%09%09success &= add(e);%0D%0A%09%09%7D%0D%0A%09%09return success
+Iterables.getLast(this)
 ;%0D%0A%09%7D%0D%0A
-%09
 %0D%0A%09p

change underlying implementation of the fixedsizesortedset to priority queue