java優先佇列,equals方法
阿新 • • 發佈:2022-04-13
優先佇列的申明:
Queue<Student> queue = new PriorityQueue<>();
要使得優先佇列的排序起作用,就要讓這個student實現Comparable中的compareTo方法
@Override public int compareTo(Object o) { Student another = (Student) o; Integer anotherAge = another.age; if (this.age < anotherAge) {return -1; } else if (this.age == anotherAge) { return 0; } return 1; }
我在這裡是按年齡排序,年齡小的返回-1,也就是正常情況下,這樣優先佇列裡每次取出的就是年齡最小的那個student
此外關於重寫equals問題
例如
@Override public boolean equals(Object obj) { Student another = (Student) obj; if (another.name.equals(this.name)) { return true; } return false; }
Student student1 = new Student("1", 20, "徐康"); Student student2 = new Student("2", 21, "徐康");
呼叫student1.equals(student2)返回true
Stack<Student> students=new Stack<>(); students.add(student1); System.out.println(students.contains(student2)); List<Student> list=new ArrayList<>(); list.add(student1); System.out.println(list.contains(student2));
兩個都輸出true