I took a look at the code in this thread: https://codereview.stackexchange.com/questions/98105/priority-stack-in-java
This implements a PriorityStack using the object and the priority. I need an implementation where you only add the object to the PriorityStack, and using the Comparable interface you can define which attribute should be prioritized.
For example:
I have a list of dogs:
- name = "Skip", age = 4
- name = "Gregory", age = 3
- name = "Ziggy", age = 4
In the Dog object I would implement the Comparable interface with:
public int compareTo(Dog other) {
if(other == null) {
return -1;
}
return this.age - other.age;
}
How can I use this to prioritize my PriorityStack?
The result of this should be the youngest dog first, and then the other 2 dogs based on First In Last Out
(Edited answer after the clarifications given in the comments)
In the PriorityStack in the link, it takes two values and stored them in a TreeMap. In your case, once you make the Dog class comparable (and the Dog objects contain a
.ageattribute) then you can store these Dog objects in a TreeSet (which is a sorted collection, sorted according to your compareTo() method in Dog).You would instantiate the TreeSet as
TreeSet<Dog> stack = new TreeSet<>();