我们知道,优先级队列在插入元素时有一个要求:需要可以比较的对象才能插入。这里我们需要知道怎样插入自定义类型对象:
比如我们插入这个 student 对象:
class student {
int age;
String name;
public student(int age, String name) {
this.age = age;
this.name = name;
}
}
public class Test {
public static void main(String[] args) {
PriorityQueue<student> priorityQueue = new PriorityQueue<>();
priorityQueue.offer(new student(12,"小猪佩奇"));
priorityQueue.offer(new student(12,"小猪乔治"));
}
在运行后发现它会报类型不兼容的异常,这是因为在堆中插入元素,为了满足堆的性质,需要进行对象的比较,但是我们的 student 类型对象时不能直接比较的,所以会报错
在 Java 中,基本类型的对象是可以直接进行比较大小的
class TestCompare {
public static void main(String[] args) {
int a = 10;
int b = 20;
System.out.println(a > b);
System.out.println(a < b);
System.out.println(a == b);
char c1 = 'A';
char c2 = 'B';
System.out.println(c1 > c2);
System.out.println(c1 < c2);
System.out.println(c1 == c2);
boolean b1 = true;
boolean b2 = false;
System.out.println(b1 == b2);
System.out.println(b1 != b2);
}
}
class Card {
public int rank; // 数值
public String suit; // 花色
public Card(int rank, String suit) {
this.rank = rank;
this.suit = suit;
}
}
public class TestPriorityQueue {
public static void main(String[] args) {
Card c1 = new Card(1, "♠");
Card c2 = new Card(2, "♠");
Card c3 = c1;
//System.out.println(c1 > c2); // 编译报错
System.out.println(c1 == c2); // 编译成功 ----> 打印false,因为c1和c2指向的是不同对象
//System.out.println(c1 < c2); // 编译报错
System.out.println(c1 == c3); // 编译成功 ----> 打印true,因为c1和c3指向的是同一个对象
}
}
这里我们知道,直接进行对象比较的是地址,只有相同才会返回 true,不同就会报错。但是这里为毛 == 可以比较呢?这就得提到 Object 类了,因为自定义类也会继承 Object 类,这个类中提供了 equal 方法,== 的情况下就是用的 Object 的equal 方法。但是这个方式比较的就是引用对象的地址,没有比较对象的内容,这就头疼了。
// Object中equal的实现,可以看到:直接比较的是两个引用变量的地址
public boolean equals(Object obj) {
return (this == obj);
}
class student {
int age;
String name;
public student(int age, String name) {
this.age = age;
this.name = name;
}
@Override
public boolean equals(Object obj) {
if(this == obj) {
return true;
}
if(obj == null || !(obj instanceof student)) {
return false;
}
student o = (student) obj;
return this.age == ((student) obj).age && this.name.equals(o.name);
}
}
如果指向一个对象,返回 true
如果传入的是 null 或者不是 student,返回 false
按照类的成员对象比较,只要成员对象相同就返回 true
注意下调其他引用类型的比较也要调用 equals
这里的缺陷就是:equals 只能按照相等来比较,不能比较大小
Comparable 接口的源码:
public interface Comparable<E> {
// 返回值:
// < 0: 表示 this 指向的对象小于 o 指向的对象
// == 0: 表示 this 指向的对象等于 o 指向的对象
// > 0: 表示 this 指向的对象大于 o 指向的对象
int compareTo(E o);
}
对用户自定义类型,想要按照大小比较时,在定义类的时候,实现 Comparable 接口即可。然后在类中实现 compareTo 方法:
class student implements Comparable<student>{
int age;
String name;
public student(int age, String name) {
this.age = age;
this.name = name;
}
@Override
public int compareTo(student o) {
if(o == null) {
return 1;
}
return this.age - o.age;
}
}
用户自定义比较器类,需要实现 Comparator 接口:
public interface Comparator<T> {
// 返回值:
// < 0: 表示 o1 指向的对象小于 o2 指向的对象
// == 0: 表示 o1 指向的对象等于 o2 指向的对象
// > 0: 表示 o1 指向的对象等于 o2 指向的对象
int compare(T o1, T o2);
}
这里要注意区分 Comparable 和 Comparator 接口
在自定义比较器类中重写 compare 方法:
import java.util.Comparator;
class Card {
public int rank; // 数值
public String suit; // 花色
public Card(int rank, String suit) {
this.rank = rank;
this.suit = suit;
}
}
class CardComparator implements Comparator<Card> {
// 根据数值比较,不管花色
// 这里我们认为 null 是最小的
@Override
public int compare(Card o1, Card o2) {
if (o1 == o2) {
return 0;
} if
(o1 == null) {
return -1;
}
if (o2 == null) {
return 1;
}
return o1.rank - o2.rank;
}
public static void main(String[] args){
Card p = new Card(1, "♠");
Card q = new Card(2, "♠");
Card o = new Card(1, "♠");
// 定义比较器对象
CardComparator cmptor = new CardComparator();
// 使用比较器对象进行比较
System.out.println(cmptor.compare(p, o)); // == 0,表示牌相等
System.out.println(cmptor.compare(p, q)); // < 0,表示 p 比较小
System.out.println(cmptor.compare(q, p)); // > 0,表示 q 比较大
}
}
这里使用 Comparator 需要导入 java.util 包
集合框架中的 PriorityQueue 底层使用堆结构,因此其内部的元素必须要能够比大小 PriorityQueue 采用了:Comparble和 Comparator 两种方式。
1. Comparble 是默认的内部比较方式,如果用户插入自定义类型对象时,该类对象必须要实现 Comparble 接口,并覆写 compareTo 方法
2. 用户也可以选择使用比较器对象,如果用户插入自定义类型对象时,必须要提供一个比较器类,让该类实现 Comparator 接口并覆写 compare 方法。
JDK中的源码:
// 用户如果没有提供比较器对象,使用默认的内部比较,将comparator置为null
public PriorityQueue() {
this(DEFAULT_INITIAL_CAPACITY, null);
}
// 如果用户提供了比较器,采用用户提供的比较器进行比较
public PriorityQueue(int initialCapacity, Comparator<? super E> comparator) {
// Note: This restriction of at least one is not actually needed,
// but continues for 1.5 compatibility
if (initialCapacity < 1)
throw new IllegalArgumentException();
this.queue = new Object[initialCapacity];
this.comparator = comparator;
}
private void siftUp(int k, E x) {
if (comparator != null)
siftUpUsingComparator(k, x);
else
siftUpComparable(k, x);
}
private void siftUpComparable(int k, E x) {
Comparable<? super E> key = (Comparable<? super E>) x;
while (k > 0) {
int parent = (k - 1) >>> 1;
Object e = queue[parent];
if (key.compareTo((E) e) >= 0)
break;
queue[k] = e;
k = parent;
}
queue[k] = key;
}
@SuppressWarnings("unchecked")
private void siftUpUsingComparator(int k, E x) {
while (k > 0) {
int parent = (k - 1) >>> 1;
Object e = queue[parent];
if (comparator.compare(x, (E) e) >= 0)
break;
queue[k] = e;
k = parent;
}
queue[k] = x;
}
画图分析:
阅读量:2031
点赞量:0
收藏量:0