/* ToDOItem * * COP 3330 * UCf - Fall 2006 * * Demonstrates use of PriorityQueue, and inheritance */ import java.util.*; public class ToDoItem implements Comparable { //instance variables: private int priority; private String description; public ToDoItem(String description, int priority){ this.description = description; this.priority = priority; } ///////////////////////////////////////////////////////////////// // accessor methods: public String getDescription(){ return this.description; } public int getPriority(){ return this.priority; } public String toString(){ return this.priority + ": " + this.description; } //////////////////////////////////////////////////////////////////// // Comparing public boolean equals (Object other){ //comparing the actual objects to see if they're the same //first make sure the right type: if (!(other instanceof ToDoItem)) return false; ToDoItem o = (ToDoItem)other;//cast so we an call ToDoItem metods if ((this.description.equals(o.description)) && (this.priority == o.priority)) //since we are in ToDoItem, we can access other's private variables return true; return false; } public int compareTo(ToDoItem other){ //returns -1, 0, 1 depending on how this compares to other //no casting necessary, because other is a ToDoItem (specified in type parameter of Comparable) //This comparison is for priority, or for ordering... if (this.equals(other)) return 0;//they're equal if (this.priority > other.priority) return -1; //this is stronger else if (this.priority < other.priority) return 1;//other is stronger else return this.description.compareTo(other.description);//must resort to comparing strings } ///////////////////////////////////////////////////////////////// // static methods: public static void main (String [] args) { ToDoItem item1 = new ToDoItem("do something", 5); ToDoItem item2 = new ToDoItem("do something else", 10); PriorityQueue toDoList = new PriorityQueue(); toDoList.add(item1); toDoList.add(item2); //print whole list: System.out.println("Call PriorityQueue's toString to get list:\n" + toDoList); //get items one at a time: System.out.println("----------------------------------"); ToDoItem item = toDoList.poll(); while (item != null){ System.out.println(item); System.out.println("<>"); ToDoItem.waitEnter(); item = toDoList.poll(); } System.out.println("--------------------------------\nNo more items, you're done!"); } public static void waitEnter(){ Scanner ent = new Scanner(System.in); ent.nextLine(); } }