# PriorityQueue
import java.util.PriorityQueue;
import java.util.Queue;
public class MyPrioirityQueue {
public static void main(String[] args) {
Queue<Person> myQueue = new PriorityQueue<>();
myQueue.add(new Person("Adam", 26));
myQueue.add(new Person("Joe", 36));
myQueue.add(new Person("Ada", 24));
// System.out.println(myQueue.peek());
while (myQueue.peek() != null)
{
System.out.print(myQueue.poll() + " ");
}
}
}
# 큐에 담을 객체
public class Person implements Comparable<Person> {
private String name;
private Integer age;
public Person(String name, Integer age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return this.name + " - " + this.age;
}
@Override
public int compareTo(Person otherPerson) {
return -Integer.compare(this.age, otherPerson.getAge());
}
}
# 실행 결과
# compareTo 메쏘드를 중복정의해서 리턴값에 -를 붙여 큰 정수부터 꺼낼때
Joe - 36 Adam - 26 Ada - 24
#
compareTo 메쏘드를 중복정의해서 리턴값에 -가 없는 경우 작은 정수부터 꺼낼때
Ada - 24 Adam - 26 Joe - 36
댓글 영역