Search code examples
javamethodsqueuepriority-queue

Java: passing queue as a method argument?


I need to create Event class and Venue class.

In Venue class, I need to put priority queue. I need to write a method which removes and displays an event from the queue, as well as showing some simple statistics: average of people on every event etc.

I am stuck on the first point - a method that will remove and show this event. Is it possible to pass the whole queue as an argument to a method? - I tried to do it but it doesn't seem to work. - (display method in Event class).

public class Event {

    private String name;
    private int time;
    private int numberOfParticipants;

    public Event(String name, int time, int numberOfParticipants) {
        this.name = name;
        this.time = time;
        this.numberOfParticipants = numberOfParticipants;
    }

   /**Getters and setters omitted**/

    @Override
    public String toString() {
        return "Wydarzenie{" +
                "name='" + name + '\'' +
                ", time=" + time +
                ", numberOfParticipants=" + numberOfParticipants +
                '}';
    }

    public void display(PriorityQueue<Event> e){
        while (!e.isEmpty()){
            System.out.println(e.remove());
        }
    }
}

Venue Class:

public class Venue {
    public static void main(String[] args) {
         PriorityQueue<Event> pq = new PriorityQueue<>(Comparator.comparing(Event::getTime));
         pq.add(new Event("stand up", 90, 200));
         pq.add(new Event("rock concert", 120, 150));
         pq.add(new Event("theatre play", 60, 120));
         pq.add(new Event("street performance", 70, 80));
         pq.add(new Event("movie", 100, 55));
    }
}

Solution

  • Here are some changes to the venue class.

    class Venue {
        PriorityQueue<Event> pq = new PriorityQueue<Event>(Comparator.comparing(Event::getTime));
    
        public static void main(String[] args) {
            Venue v = new Venue();
            v.addEvents();
            v.display(v.pq);
        }
    
        private void addEvents() {
            pq.add(new Event("stand up", 90, 200));
            pq.add(new Event("rock concert", 120, 150));
            pq.add(new Event("theatre play", 60, 120));
            pq.add(new Event("street performance", 70, 80));
            pq.add(new Event("movie", 100, 55));
        }
    
        private void display(PriorityQueue<Event> e) {
            while (!e.isEmpty()) {
                System.out.println(e.remove());
            }
        }
    }
    

    The queue is at the class level so each Venue can have its own queue. The main method just calls other methods but ideally should be placed in a different class. The display will be called on Venue instance and you can do your statistics in that method while removing each item from the queue.