java优先队列,equals方法
优先队列的申明:
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

浙公网安备 33010602011771号