代码之家  ›  专栏  ›  技术社区  ›  bryniek

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

  •  0
  • bryniek  · 技术社区  · 7 年前

    我需要创建 Event 类别和 Venue

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

    我被第一点困住了,这是一种将删除并显示此事件的方法。是否可以将整个队列作为参数传递给方法?-我试着这么做,但似乎不起作用。-(中的显示方法 事件 类)。

    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));
        }
    }
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   clinomaniac    7 年前

    以下是对场地类的一些更改。

    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方法只调用其他方法,但理想情况下应该放在不同的类中。该显示将在场馆实例上调用,您可以使用该方法进行统计,同时从队列中删除每个项目。