java中各種對象的比較方法
前言
今天為大家?guī)淼氖?java對象的比較 相關內(nèi)容的講解!??
1. 問題提出
上節(jié)課我們講了優(yōu)先級隊列,優(yōu)先級隊列在插入元素時有個要求:插入的元素不能是null或者元素之間必須要能夠進行比較,為了簡單起見,我們只是插入了Integer類型,那優(yōu)先級隊列中能否插入自定義類型對象呢?

class Card {
public int rank; // 數(shù)值
public String suit; // 花色
public Card(int rank, String suit) {
this.rank = rank;
this.suit = suit;
}
}
public class TestPriorityQueue {
public static void TestPriorityQueue()
{
PriorityQueue<Card> p = new PriorityQueue<>();
p.offer(new Card(1, "?"));
p.offer(new Card(2, "?"));
}
public static void main(String[] args) {
TestPriorityQueue();
}
}
優(yōu)先級隊列底層使用堆,而向堆中插入元素時,為了滿足堆的性質(zhì),必須要進行元素的比較,而此時Card是沒有辦法直接進行比較的,因此拋出異常。

2. 元素的比較
2.1 基本類型的比較
在Java中,基本類型的對象可以直接比較大小。
public 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);
}
}
2.2 對象的比較
class Card {
public int rank; // 數(shù)值
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指向的是同一個對象
}
}
c1、c2和c3分別是Card類型的引用變量,上述代碼在比較編譯時:
c1 > c2 編譯失敗
c1== c2 編譯成功
c1 < c2 編譯失敗
從編譯結果可以看出,Java中引用類型的變量不能直接按照 > 或者 < 方式進行比較。 那為什么==可以比較?
因為:對于用戶實現(xiàn)自定義類型,都默認繼承自Object類,而Object類中提供了equal方法,而==默認情況下調(diào)用的就是equal方法,但是該方法的比較規(guī)則是:沒有比較引用變量引用對象的內(nèi)容,而是直接比較引用變量的地址,但有些情況下該種比較就不符合題意。
// Object中equal的實現(xiàn),可以看到:直接比較的是兩個引用變量的地址
public boolean equals(Object obj) {
return (this == obj);
}
3. 對象的比較
有些情況下,需要比較的是對象中的內(nèi)容,比如:向優(yōu)先級隊列中插入某個對象時,需要對按照對象中內(nèi)容來調(diào)整堆,那該如何處理呢?
3.1 覆寫基類的equal
public class Card {
public int rank; // 數(shù)值
public String suit; // 花色
public Card(int rank, String suit) {
this.rank = rank;
this.suit = suit;
}
@Override
public boolean equals(Object o) {
// 自己和自己比較
if (this == o) {
return true;
}
// o如果是null對象,或者o不是Card的子類
if (o == null || !(o instanceof Card)) {
return false;
}
// 注意基本類型可以直接比較,但引用類型最好調(diào)用其equal方法
Card c = (Card)o;
return rank == c.rank
&& suit.equals(c.suit);
}
}
注意: 一般覆寫 equals 的套路就是上面演示的
- 如果指向同一個對象,返回 true
- 如果傳入的為 null,返回 false
- 如果傳入的對象類型不是 Card,返回 false
- 按照類的實現(xiàn)目標完成比較,例如這里只要花色和數(shù)值一樣,就認為是相同的牌
- 注意下調(diào)用其他引用類型的比較也需要 equals,例如這里的 suit 的比較
覆寫基類equal的方式雖然可以比較,但缺陷是:equal只能按照相等進行比較,不能按照大于、小于的方式進行比較。
3.2 基于Comparble接口類的比較
Comparble是JDK提供的泛型的比較接口類,源碼實現(xiàn)具體如下:
public interface Comparable<E> {
// 返回值:
// < 0: 表示 this 指向的對象小于 o 指向的對象
// == 0: 表示 this 指向的對象等于 o 指向的對象
// > 0: 表示 this 指向的對象等于 o 指向的對象
int compareTo(E o);
}
對用用戶自定義類型,如果要想按照大小與方式進行比較時:在定義類時,實現(xiàn)Comparble接口即可,然后在類中重寫compareTo方法。
public class Card implements Comparable<Card> {
public int rank; // 數(shù)值
public String suit; // 花色
public Card(int rank, String suit) {
this.rank = rank;
this.suit = suit;
}
// 根據(jù)數(shù)值比較,不管花色
// 這里我們認為 null 是最小的
@Override
public int compareTo(Card o) {
if (o == null) {
return 1;
}
return rank - o.rank;
}
public static void main(String[] args){
Card p = new Card(1, "?");
Card q = new Card(2, "?");
Card o = new Card(1, "?");
System.out.println(p.compareTo(o)); // == 0,表示牌相等
System.out.println(p.compareTo(q));// < 0,表示 p 比較小
System.out.println(q.compareTo(p));// > 0,表示 q 比較大
}
}Compareble是java.lang中的接口類,可以直接使用。
3.3 基于比較器比較
按照比較器方式進行比較,具體步驟如下:
用戶自定義比較器類,實現(xiàn)Comparator接口
public interface Comparator<T> {
// 返回值:
// < 0: 表示 o1 指向的對象小于 o2 指向的對象
// == 0: 表示 o1 指向的對象等于 o2 指向的對象
// > 0: 表示 o1 指向的對象等于 o2 指向的對象
int compare(T o1, T o2);
}
注意:區(qū)分Comparable和Comparator。
覆寫Comparator中的compare方法
import java.util.Comparator;
class Card {
public int rank; // 數(shù)值
public String suit; // 花色
public Card(int rank, String suit) {
this.rank = rank;
this.suit = suit;
}
}
class CardComparator implements Comparator<Card> {
// 根據(jù)數(shù)值比較,不管花色
// 這里我們認為 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 包中的泛型接口類,使用時必須導入對應的包。
3.4 三種方式對比

4. 集合框架中PriorityQueue的比較方式
集合框架中的PriorityQueue底層使用堆結構,因此其內(nèi)部的元素必須要能夠比大小,PriorityQueue采用了:Comparble和Comparator兩種方式。
Comparble是默認的內(nèi)部比較方式,如果用戶插入自定義類型對象時,該類對象必須要實現(xiàn)Comparble接口,并覆寫compareTo方法- 用戶也可以選擇使用比較器對象,如果用戶插入自定義類型對象時,必須要提供一個比較器類,讓該類實現(xiàn)
Comparator接口并覆寫compare方法。
// JDK中PriorityQueue的實現(xiàn):
public class PriorityQueue<E> extends AbstractQueue<E>
implements java.io.Serializable {
// ...
// 默認容量
private static final int DEFAULT_INITIAL_CAPACITY = 11;
// 內(nèi)部定義的比較器對象,用來接收用戶實例化PriorityQueue對象時提供的比較器對象
private final Comparator<? super E> comparator;
// 用戶如果沒有提供比較器對象,使用默認的內(nèi)部比較,將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;
}
// ...
// 向上調(diào)整:
// 如果用戶沒有提供比較器對象,采用Comparable進行比較
// 否則使用用戶提供的比較器對象進行比較
private void siftUp(int k, E x) {
if (comparator != null)
siftUpUsingComparator(k, x);
else
siftUpComparable(k, x);
}
// 使用Comparable
@SuppressWarnings("unchecked")
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;
}
}
5. 模擬實現(xiàn)PriorityQueue
class LessIntComp implements Comparator<Integer>{
@Override
public int compare(Integer o1, Integer o2) {
return o1 - o2;
}
}
class GreaterIntComp implements Comparator<Integer>{
@Override
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
}
// 假設:創(chuàng)建的是小堆----泛型實現(xiàn)
public class MyPriorityQueue<E> {
private Object[] hp;
private int size = 0;
private Comparator<? super E> comparator = null;
// java8中:優(yōu)先級隊列的默認容量是11
public MyPriorityQueue(Comparator<? super E> com) {
hp = new Object[11];
size = 0;
comparator = com;
}
public MyPriorityQueue() {
hp = new Object[11];
size = 0;
comparator = null;
}
// 按照指定容量設置大小
public MyPriorityQueue(int capacity) {
capacity = capacity < 1 ? 11 : capacity;
hp = new Object[capacity];
size = 0;
}
// 注意:沒有此接口,給學生強調(diào)清楚
// java8中:可以將一個集合中的元素直接放到優(yōu)先級隊列中
public MyPriorityQueue(E[] array){
// 將數(shù)組中的元素放到優(yōu)先級隊列底層的容器中
hp = Arrays.copyOf(array, array.length);
size = hp.length;
// 對hp中的元素進行調(diào)整
// 找到倒數(shù)第一個非葉子節(jié)點
for(int root = ((size-2)>>1); root >= 0; root--){
shiftDown(root);
}
}
// 插入元素
public void offer(E val){
// 先檢測是否需要擴容
grow();
// 將元素放在最后位置,然后向上調(diào)整
hp[size] = val;
size++;
shiftUp(size-1);
}
// 刪除元素: 刪除堆頂元素
public void poll(){
if(isEmpty()){
return;
}
// 將堆頂元素與堆中最后一個元素進行交換
swap((E[])hp, 0, size-1);
// 刪除最后一個元素
size--;
// 將堆頂元素向下調(diào)整
shiftDown(0);
}
public int size(){
return size;
}
public E peek(){
return (E)hp[0];
}
boolean isEmpty(){
return 0 == size;
}
// 向下調(diào)整
private void shiftDown(int parent){
if(null == comparator){
shiftDownWithcompareTo(parent);
}
else{
shiftDownWithComparetor(parent);
}
}
// 使用比較器比較
private void shiftDownWithComparetor(int parent){
// child作用:標記最小的孩子
// 因為堆是一個完全二叉樹,而完全二叉樹可能有左沒有有
// 因此:默認情況下,讓child標記左孩子
int child = parent * 2 + 1;
// while循環(huán)條件可以一直保證parent左孩子存在,但是不能保證parent的右孩子存在
while(child < size)
{
// 找parent的兩個孩子中最小的孩子,用child進行標記
// 注意:parent的右孩子可能不存在
// 調(diào)用比較器來進行比較
if(child+1 < size && comparator.compare((E)hp[child+1], (E)hp[child]) < 0 ){
child += 1;
}
// 如果雙親比較小的孩子還大,將雙親與較小的孩子交換
if(comparator.compare((E)hp[child], (E)hp[parent]) < 0) {
swap((E[])hp, child, parent);
// 小的元素往下移動,可能導致parent的子樹不滿足堆的性質(zhì)
// 因此:需要繼續(xù)向下調(diào)整
parent = child;
child = child*2 + 1;
}
else{
return;
}
}
}
// 使用compareTo比較
private void shiftDownWithcompareTo(int parent){
// child作用:標記最小的孩子
// 因為堆是一個完全二叉樹,而完全二叉樹可能有左沒有有
// 因此:默認情況下,讓child標記左孩子
int child = parent * 2 + 1;
// while循環(huán)條件可以一直保證parent左孩子存在,但是不能保證parent的右孩子存在
while(child < size)
{
// 找parent的兩個孩子中最小的孩子,用child進行標記
// 注意:parent的右孩子可能不存在
// 向上轉(zhuǎn)型,因為E的對象都實現(xiàn)了Comparable接口
if(child+1 < size && ((Comparable<? super E>)hp[child]).
compareTo((E)hp[child])< 0){
child += 1;
}
// 如果雙親比較小的孩子還大,將雙親與較小的孩子交換
if(((Comparable<? super E>)hp[child]).compareTo((E)hp[parent]) < 0){
swap((E[])hp, child, parent);
// 小的元素往下移動,可能導致parent的子樹不滿足堆的性質(zhì)
// 因此:需要繼續(xù)向下調(diào)整
parent = child;
child = child*2 + 1;
}
else{
return;
}
}
}
// 向上調(diào)整
void shiftUp(int child){
if(null == comparator){
shiftUpWithCompareTo(child);
}
else{
shiftUpWithComparetor(child);
}
}
void shiftUpWithComparetor(int child){
// 獲取孩子節(jié)點的雙親
int parent = ((child-1)>>1);
while(0 != child){
// 如果孩子比雙親還小,則不滿足小堆的性質(zhì),交換
if(comparator.compare((E)hp[child], (E)hp[parent]) < 0){
swap((E[])hp, child, parent);
child = parent;
parent = ((child-1)>>1);
}
else{
return;
}
}
}
void shiftUpWithCompareTo(int child){
// 獲取孩子節(jié)點的雙親
int parent = ((child-1)>>1);
while(0 != child){
// 如果孩子比雙親還小,則不滿足小堆的性質(zhì),交換
if(((Comparable<? super E>)hp[child]).compareTo((E)hp[parent]) < 0){
swap((E[])hp, child, parent);
child = parent;
parent = ((child-1)>>1);
}
else{
return;
}
}
}
void swap(E[] hp, int i, int j){
E temp = hp[i];
hp[i] = hp[j];
hp[j] = temp;
}
// 仿照JDK8中的擴容方式,注意還是有點點的區(qū)別,具體可以參考源代碼
void grow(){
int oldCapacity = hp.length;
if(size() >= oldCapacity){
// Double size if small; else grow by 50%
int newCapacity = oldCapacity + ((oldCapacity < 64) ?
(oldCapacity + 2) :
(oldCapacity >> 1));
hp = Arrays.copyOf(hp, newCapacity);
}
}
public static void main(String[] args) {
int[] arr = {4,1,9,2,8,0,7,3,6,5};
// 小堆---采用比較器創(chuàng)建小堆
MyPriorityQueue<Integer> mq1 = new MyPriorityQueue(new LessIntComp());
for(int e : arr){
mq1.offer(e);
}
// 大堆---采用比較器創(chuàng)建大堆
MyPriorityQueue<Integer> mq2 = new MyPriorityQueue(new GreaterIntComp());
for(int e : arr){
mq2.offer(e);
}
// 小堆--采用CompareTo比較創(chuàng)建小堆
MyPriorityQueue<Integer> mq3 = new MyPriorityQueue();
for(int e : arr){
mq3.offer(e);
}
}
}總結
到此這篇關于java中各種對象的比較方法的文章就介紹到這了,更多相關java對象比較內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Java實現(xiàn)文件壓縮與解壓的示例[zip格式,gzip格式]
本篇文章主要介紹了Java實現(xiàn)文件壓縮與解壓的示例[zip格式,gzip格式],具有一定的參考價值,感興趣的小伙伴們可以參考一下。2017-01-01
Java的Flowable工作流之加簽轉(zhuǎn)簽詳解
這篇文章主要介紹了Java的Flowable工作流之加簽轉(zhuǎn)簽詳解,Flowable是一個開源的工作流引擎,它提供了一套強大的工具和功能,用于設計、執(zhí)行和管理各種類型的工作流程,需要的朋友可以參考下2023-11-11
Mybatis返回值(resultType&resultMap)的具體使用
返回值屬性有兩種設置,一種是resultType,一種是resultMap,本文主要介紹了Mybatis返回值(resultType&resultMap)的具體使用,具有一定的參考價值,感興趣的可以了解一下2023-08-08
SpringBoot2.0 整合 Dubbo框架實現(xiàn)RPC服務遠程調(diào)用方法
這篇文章主要介紹了SpringBoot2.0 整合 Dubbo框架 實現(xiàn)RPC服務遠程調(diào)用 ,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-07-07

