I implemented a fixed sized priority queue. How can I improve my code?
public class FixedSizedPriorityQueue {
private final int capacity;
private boolean sorted = false;
private double smallest = Double.POSITIVE_INFINITY;
private ArrayList<Double> list;
protected static final Comparator<Double> comparator = new Comparator<Double>() {
@Override
public int compare(Double o1, Double o2) {
return o2.compareTo(o1);
}
};
public FixedSizedPriorityQueue(int capacity) {
this.capacity = capacity;
list = new ArrayList<Double>(capacity);
}
public void add(double value) {
if (list.size() < capacity) {
list.add(value);
sorted = false;
if (value < smallest) {
smallest = value;
}
} else {
if (value > smallest) {
if (!sorted) {
Collections.sort(list, comparator);
sorted = true;
}
list.set(capacity - 1, value);
if (list.get(capacity - 2) > value) {
smallest = value;
} else {
smallest = list.get(capacity - 2);
sorted = false;
}
}
}
}
public int getSize() {
return list.size();
}
public Double poll() {
if (list.size() == 0) return null;
if (!sorted) {
Collections.sort(list, comparator);
sorted = true;
}
Double value = list.get(0);
list.remove(0);
if (list.size() == 0) smallest = Double.POSITIVE_INFINITY;
return value;
}
public void print() {
for (int i = 0; i < list.size(); i++) {
System.out.println(i + ": " + list.get(i));
}
System.out.println("Smallest: " + smallest);
}
}