繁体   English   中英

Java:将队列作为方法参数传递?

[英]Java: passing queue as a method argument?

我需要创建Event类和Venue类。

Venue类中,我需要放置优先级队列。 我需要编写一个从队列中删除并显示事件的方法,以及显示一些简单的统计信息:每个事件的平均人数等。

我停留在第一点上-一种将删除并显示此事件的方法。 是否可以将整个队列作为参数传递给方法? -我尝试这样做,但是似乎没有用。 -( Event类中的显示方法)。

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());
        }
    }
}

场地类别:

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));
    }
}

这是对场地课程的一些更改。

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());
        }
    }
}

队列处于课程级别,因此每个场所都可以有自己的队列。 main方法仅调用其他方法,但理想情况下应将其放在其他类中。 该显示将在Venue实例上调用,您可以在从队列中删除每个项目的同时,使用该方法进行统计。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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