简体   繁体   中英

Java: Queues within A class

I have created a class Book that has a queue of another class I created, Employees as seen below...

class Employee{
String name;
int waiting_time;
int retaining_time;
int priority;

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

//getters and setters ommitted to save space

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

public int getPriority()
{
    return priority;
}
}

class Book{
String name;
LocalDate start_date;
LocalDate end_date;
boolean archived;
Queue<Employee> Employees ;

public Book()
{

}

//getters and setters for end_date, start_date, archived ommitted to save space

public void setQueue(Queue<Employee> qa)
{
    Employees = qa;
}

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

When I attempt to add an Employee to the Book's queue...

public static void addEmployee(String aName, ArrayList<Book> booksToCirculate, ArrayList<Employee> employeeArray)
{
    Employee anEmployee = new Employee();
    anEmployee.setName(aName);
    employeeArray.add(anEmployee);
    for (Book b : booksToCirculate)
    {
        b.getQueue().add(anEmployee); //adds employee to each queue, where the error is at
    }

}

I receive a NullPointerException error when trying to add an Employee to the queue and I can't seem to figure out why, I've gone through my book, and it appears as if I've done it according to an example of dogs and dogtoy's they had. Any suggestions on where I'm going wrong are much appreciated!

Also, if you have any questions on my code please ask, I'm rather new at classes and objects, but will do my best to explain myself!

It looks you need to create your queue. As you have not, it defaults to null . Hence:

b.getQueue()

is returning null .

So when you call

b.getQueue().add(...)

you are trying to call a method on null which causes the exception.

If this is the case, then the solution would be to create the queue in the Book constructor:

public Book()
{
     Employees = new Deque<Employee>(); // pick an implementation of the Queue interface
}

You did not initialize the Queue . You have to initialize it before accessing it, otherwise it's initialized with null by the compiler.

Sonce Queue is an Interface you can't do

    Queue<Employee> Employees = new Queue<>(); //won't work, because Queue is an interface

What you could do is use a LinkedList which implemens Queue :

    Queue<Employee> Employees = new LinkedList<>();

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