Related questions:
Create a PriorityQueue that has size limit. It stores N max numbers.
import java.util.*;
class Demo
{
public static > PriorityQueue getPq(final int n, Comparator comparator)
{
return new PriorityQueue(comparator)
{
boolean full()
{
return size() >= n;
}
@Override
public boolean add(E e)
{
if (!full())
{
return super.add(e);
}
else if (peek().compareTo(e) < 0)
{
poll();
return super.add(e);
}
return false;
}
@Override
public boolean offer(E e)
{
if (!full())
{
return super.offer(e);
}
else if (peek().compareTo(e) < 0)
{
poll();
return super.offer(e);
}
return false;
}
};
}
public static void printq(PriorityQueue pq)
{
Object o = null;
while ((o = pq.poll()) != null)
{
System.out.println(o);
}
}
public static void main (String[] args)
{
PriorityQueue pq = getPq(2, new Comparator(){
@Override
public int compare(Integer i1, Integer i2)
{
return i1.compareTo(i2);
}
});
pq.add(4);
pq.add(1);
pq.add(5);
pq.add(2);
printq(pq);
}
}