Select Git revision
MailPool.java 2.63 KiB
package automail;
import java.util.LinkedList;
import java.util.Comparator;
import java.util.ListIterator;
import exceptions.ItemTooHeavyException;
/**
* addToPool is called when there are mail items newly arrived at the building to add to the MailPool or
* if a robot returns with some undelivered items - these are added back to the MailPool.
* The data structure and algorithms used in the MailPool is your choice.
*
*/
public class MailPool {
private class Item {
int destination;
MailItem mailItem;
// Use stable sort to keep arrival time relative positions
public Item(MailItem mailItem) {
destination = mailItem.getDestFloor();
this.mailItem = mailItem;
}
}
public class ItemComparator implements Comparator<Item> {
@Override
public int compare(Item i1, Item i2) {
int order = 0;
if (i1.destination < i2.destination) {
order = 1;
} else if (i1.destination > i2.destination) {
order = -1;
}
return order;
}
}
private LinkedList<Item> pool;
private LinkedList<Robot> robots;
public MailPool(int nrobots){ //does it need a number of robots??????
// Start empty
pool = new LinkedList<Item>();
robots = new LinkedList<Robot>();
}
/**
* Adds an item to the mail pool
* @param mailItem the mail item being added.
*/
public void addToPool(MailItem mailItem) {
Item item = new Item(mailItem);
pool.add(item);
pool.sort(new ItemComparator());
}
/**
* load up any waiting robots with mailItems, if any.
*/
public void loadItemsToRobot() throws ItemTooHeavyException {
//List available robots
ListIterator<Robot> i = robots.listIterator();
while (i.hasNext()) loadItem(i);
}