[우선순위 큐] 정렬 기준

10370 단어 JavaJava

Collections

//int형 priorityQueue 선언 (우선순위가 낮은 숫자 순)
PriorityQueue<Integer> priorityQueue = new PriorityQueue<>();

//int형 priorityQueue 선언 (우선순위가 높은 숫자 순)
PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(Collections.reverseOrder());

//String형 priorityQueue 선언 (우선순위가 낮은 숫자 순)
PriorityQueue<String> priorityQueue = new PriorityQueue<>(); 

//String형 priorityQueue 선언 (우선순위가 높은 숫자 순)
PriorityQueue<String> priorityQueue = new PriorityQueue<>(Collections.reverseOrder());

사용자 정의 Comparable

class Student implements Comparable<Student> {
    String name;
    int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public int compareTo(Student target) {
        return this.age <= target.age ? 1 : - 1;
    }

    @Override
    public String toString() {
        return "이름 : " + name + ", 나이 : " + age;
    }
}

static PriorityQueue<Student> getPriorityQueueOfStudents() {
    PriorityQueue<Student> priorityQueue = new PriorityQueue<>();

    priorityQueue.offer(new Student("김철수", 20));
    priorityQueue.offer(new Student("김영희", 100));
    priorityQueue.offer(new Student("한택희", 66));
    priorityQueue.offer(new Student("이나영", 7));
    priorityQueue.offer(new Student("이혁", 43));
    priorityQueue.offer(new Student("안영희", 100));

    return priorityQueue;
}

좋은 웹페이지 즐겨찾기