简体   繁体   中英

Java: Sorting a Queue of Objects

I'm studying for an upcoming test, and came across a rather interesting problem. I'm attempting to order a queue of employees inside an array of objects, Books . I'm trying to order them in from highest to lowest based on the employee's priority.

class Employee{
String name;
int waiting_time;
int retaining_time;
int priority;
Book aBook;
ArrayList <Book> booksRead = new ArrayList<Book>();

public Employee()
{
    this.waiting_time=0;
    this.retaining_time=0;
}

    public int getWaitingTime()
{
    return waiting_time;
}

public void setRetainingTime(int retainingtime)
{
    retaining_time = retainingtime;
}

public int getRetainingTime()
{
    return retaining_time;
}

public void setPriority()
{
    priority = waiting_time - retaining_time;
}

public int getPriority()
{
    return priority;  //sort on
}


}

class Book{
String name;
LocalDate start_date;
LocalDate end_date;
boolean archived;
Queue<Employee> Employees = new LinkedList<>();

public Book()
{

}

//getters and setters omitted
public void setQueue(Queue<Employee> qa)
{
    Employees = qa;
}

public Queue<Employee> getQueue()
{
    return Employees;
}
}

My idea was add all of the elements in the queue, all the employees, into an ArrayList, sort them, and then push them one at a time back into the queue, but that doesn't work due to multiple errors. Any and all help is much appreciated!

My idea

public static void reorder(ArrayList <Book> booksToCirculate)
{
    ArrayList <Book> tmp = new ArrayList <Book>();
    for (Book b : booksToCirculate)
    {
        tmp.add(b);
    }
    tmp.sort(b.get); // I wanted to sort on the priority here, but i'm not sure how to
}

I'd wonder why your Employee isn't Comparable :

public class Employee implements Comparable<Employee> {

    private int priority;

    public class Employee(int p) { 
        this.priority = p;
    }

    public int compare(Employee that) {
        return this.priority - that.priority;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM