This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money. @[TOC]

One: the question elicits

When using priority queues (heaps), priority queues require that the inserted elements be comparable to each other and not null. So how do you compare objects of custom classes?


@TOC

Two: Several ways to compare in Java


2.1 Primitive types can be compared directly in 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);
}
}

Copy the code

Output result:

For primitive types, comparisons can be made with other symbols such as’ = ‘, ‘>’, ‘<‘ and return true or false.

2.2 Object Comparison

1. The introduction of

class Card {
public int rank; / / values
public String suit; / / design and color
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); // Compile error
System.out.println(c1 == c2); // compiled successfully ----> Print false because c1 and c2 point to different objects
//System.out.println(c1 < c2); // Compile error
System.out.println(c1 == c3); ----> print true, since c1 and c3 point to the same object}}Copy the code

You can see from the results that Java reference types cannot be compared directly with ‘<‘, ‘>’. The compiler gives an error, so why does’ == ‘work? The Object class provides the equal method, and ‘==’ is used by default. Equal does not compare the values of two variables, but directly compares the addresses of two reference variables.

Three: object comparison

3.1 Overrides the equal method of the base class

In 2.2, the custom equal method compares the addresses of two variables instead of their sizes. We can override the equal method of the base class

@Override
public boolean equals(Object o) {
// Compare yourself to yourself
if (this == o) {
return true;
}
// o if the object is null, or o is not a subclass of Card
if (o == null| |! (oinstanceof Card)) {
return false; } / / Note that primitive types can be compared directly, but reference types are better off calling their equal method Card c = (Card)o;returnrank == c.rank && suit.equals(c.suit); }}Copy the code

The overwrite format is much the same. Return true if both variables refer to the same variable; 2. If any of the variables passed are null, return false; 3. If the type passed is different (not “card” in the example above), also return false; 4. According to class the implementation of the target, for example here as long as the specifications and values, is considered to be the same card summary: although you can override a base class equal way comparison, but defect is: equal can only be carried out in accordance with the equal comparison, not in the manner of greater than, less than the comparison.


3.2 Comparison based on the Comparble interface class

Comparble is a generic comparison interface class provided by JDK. The source code is as follows:

public interface Comparable<E> {
// Return value:
// < 0: indicates that the object to which this refers is smaller than the object to which o refers
// == 0: indicates that the object to which this refers is equal to the object to which o refers
// > 0: indicates that the object to which this refers is equal to the object to which o refers
int compareTo(E o);
}
 public class Card implements Comparable<Card> {
public int rank; / / values
public String suit; / / design and color
public Card(int rank, String suit) {
this.rank = rank;
this.suit = suit; } / / By numerical comparison, regardless of color// Here we consider null to be minimal
@Override
public int compareTo(Card o) {
if (o == null) {
return 1;
} r
eturn rank - o.rank;
} p
ublic 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, indicating that cards are equal
System.out.println(p.compareTo(q));< 0, p is small
System.out.println(q.compareTo(p));// > 0 indicates that q is large}}Copy the code

3.3 Comparator-based comparison

The specific steps are as follows: 1: Define a Comparator class to implement the Comparator interface

public interface Comparator<T> {
// Return value:
// < 0: the object o1 points to is smaller than the object o2 points to
// == 0: indicates that the object pointed by o1 is equal to the object pointed by O2
// > 0: indicates that the object o1 points to is equal to the object o2 points to
int compare(T o1, T o2);
}

Copy the code

2: overwrite the compare method ‘in the Comparator

import java.util.Comparator;
class Card {
public int rank; / / values
public String suit; / / design and color
public Card(int rank, String
this.rank = rank;
this.suit = suit; }} c lass CardComparator implements cnullIs the smallest@Override
public int compare(Card o1, Card o2) {
if (o1 == o2) {
return 0;
} i
f (o1 == null) {
return -1;
} i
f (o2 == null) {
return 1;
} r
eturn o1.rank - o2.rank;
} p
ublic static void main(String[] args){
Card p = new Card(1."♠");
Card q = new Card(2."♠");
Card o = new Card(1."♠");
// Define a comparator object
CardComparator cmptor = new CardComparator();
// Use the comparator object for comparison
System.out.println(cmptor.compare(p, o)); // == 0, indicating that cards are equal
System.out.println(cmptor.compare(p, q)); < 0, p is small
System.out.println(cmptor.compare(q, p)); // > 0 indicates that q is large}}Copy the code

3.4 Comparison of the three comparison methods

Four: the ending

The above method is commonly used in Java to compare variables, because of the different intrusion, need to choose with the requirements.