Well, as you are should be familiar to an Queue in Java. A brief synopsis of a queue, is think of it as a line in a fast food chain. We have an X amount of people, where X is equal to 6. So we declare a new line of people to go the register.
Code:
private Queue<Persons> awaiting = new LinkedList<Persons>();
Now, we have an empty queue of persons awaiting to be ordered and get there food, so to add an person into the list we have 2 options.
Code:
awaiting.add(new Persons());
which will insert an element into the queue, the element being the person.
Or, we could also do
Code:
awaiting.offer(new Persons());
Where as, this will inset an element into the queue without violating the initial capacity of the queue.
So now, say we are going to queue these by an priority based on age, so we're an age friendly restaurant, and we serve the elderly first, well. For this, to be simpler we would use an PriorityQueue.
First, we need to design a new PriorityQueue to add the persons into.
Code:
private PriorityQueue<Persons> sortedAwaiting = new PriorityQueue<Persons>();
Now, this code needs to be modified and I will do this step by step.
Step 1) The initial capacity, the queue needs to know the initial capacity off the queue we're adding/removing from. So, say we can only serve 25 people, because that's all that will fit into the restaurant, so we add that as the capacity.
Code:
private PriorityQueue<Persons> sortedAwaiting = new PriorityQueue<Persons>(25);
Finally, we need to compare the priorities (age) of each consumer in the line, so we need to use an Comparator, here is an example.
Code:
PriorityQueue<Persons> sortedAwaiting = new PriorityQueue<Persons>(25, new Comparator<Persons>() {
@Override
public int compare(Persons o1, Persons o2) {
return o1.getAge() - o2.getAge();
}
});
Now, we have successfully created an assorted queue based on the age numbers of the consuming, and finally we need to add the queue like so.
Code:
for(Persons person : awaiting)
sortedAwaiting.offer(person);
Just thought everyone should find a better way to sort instead of doing it a more complex way, thank you.