【问题标题】:Java: passing queue as a method argument?Java:将队列作为方法参数传递?
【发布时间】:2017-12-19 00:44:48
【问题描述】:

我需要创建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));
    }
}

【问题讨论】:

  • 是的,您可以将集合作为参数传递给方法。您在尝试时遇到了什么问题?
  • 是的。您可以在方法中传递任何集合。其他几件事......我相信你应该只在 Venue 类中排队。您可以在 Venue 类中添加方法来显示它并添加事件和其他内容。主要可以调用 display(pq);另外..我不确定删除要显示的每个项目是否合适。

标签: java methods queue priority-queue


【解决方案1】:

以下是场地等级的一些变化。

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 实例上调用显示,您可以在该方法中进行统计,同时从队列中删除每个项目。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-22
    • 2017-08-21
    • 1970-01-01
    • 1970-01-01
    • 2016-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多