当前位置:网站首页>Do you know how to compare two objects

Do you know how to compare two objects

2022-06-26 18:10:00 A goblin

One , Comparison of equal object values

1, == VS equals

  • p == q It means p and q Two references point to the same object
  • p.equals(q) Express p Object to point to and q Whether the object pointed to is semantically equivalent

2, Code example

overwrite equals front

class Card {
      // Poker 
    public String rank;  // points 
    public String suit;  // Design and color 

    public Card(String rank, String suit) {
    
        this.rank = rank;
        this.suit = suit;
    }

}
public class TestCompare {
    
    public static void main(String[] args) {
    
        Card p = new Card("3","");
        Card q = new Card("3","");
        Card o = p;
        System.out.println(o == p);  // test  ==  Compare identity 
        System.out.println(p == q);
        System.out.println("===============================");
        System.out.println(p.equals(o));  // Test the comparison content 
        System.out.println(p.equals(q));  // Without rewriting , It uses Object Original in equals Method , What is equivalent to still comparing is identity 
    }
}

Running results :
 Insert picture description here
overwrite equals after

class Card {
    
    public String rank;  // points 
    public String suit;  // Design and color 

    public Card(String rank, String suit) {
    
        this.rank = rank;
        this.suit = suit;
    }
    @Override
    public boolean equals(Object obj) {
    
        // Compare by value this and obj
        // 1, Compare yourself with yourself 
        if(this == obj){
    
            return true;
        }
        //2,obj by null The situation of 
        if(obj == null){
    
            return false;
        }
        //3,obj Type is not current card type 
        if(! (obj instanceof Card) ){
    
            return false;
        }
        //4, The real comparison content 
        Card other = (Card)obj;
        return this.rank.equals(other.rank) && this.suit.equals(other.suit);

    }

}
public class TestCompare {
    
    public static void main(String[] args) {
    
        Card p = new Card("3","");
        Card q = new Card("3","");
        Card o = p;
        System.out.println(o == p);  // test  ==  Compare identity 
        System.out.println(p == q);
        System.out.println("===============================");
        System.out.println(p.equals(o));  // Test the comparison content 
        System.out.println(p.equals(q));  // After rewriting 
    }
}

 Insert picture description here
Be careful : General override equals The routine is demonstrated above

  1. If you point to the same object , return true
  2. If the incoming is null, return false
  3. If the object type passed in is not Card, return false
  4. Complete the comparison according to the implementation goal of the class , For example, as long as the design and color are the same as the value , Think it's the same card
  5. Note that the comparison of calling other reference types also needs equals, Like here suit Comparison

Two , About object values greater than 、 be equal to 、 Comparison of less than - Based on natural order

1, know Comparable

public interface Comparable<E> {
      
          //  Return value :
         // < 0:  Express  this  The object pointed to is less than  o  Object to point to  
         // == 0:  Express  this  The object pointed to is equal to  o  Object to point to 
        // > 0:  Express  this  The object pointed to is equal to  o  Object to point to  
         int compareTo(E o);
       }

2, Code example

package java15_20200510;

class Card implements Comparable<Card>{
    
    public String rank;  // points 
    public String suit;  // Design and color 

    public Card(String rank, String suit) {
    
        this.rank = rank;
        this.suit = suit;
    }
    @Override
    public int compareTo( Card o) {
    
        // If this Than o Small , Returns a less than 0 The integer of 
        // If this Than o Big , Return a greater than 0 The integer of 
        // If this == o, return 0
        if(o == null){
    
            // Generally we think that this Than o Big ,null The relatively small 
            return  1;
        }
        // Point value 2-10. JQKA
        int rank1 = this.getValue();
        int rank2 = o.getValue();
        return rank1-rank2;
    }
    public int getValue(){
    
        // In this way String The type becomes an integer number of points 
        int value = 0;
        if("j".equals(rank)){
    
            value =  10;
        } else if("Q".equals(rank)){
    
            value = 11;
        } else if("k".equals(rank)){
    
            value = 12;
        } else if("A".equals(rank)){
    
            value = 14;
        } else {
    
            value = Integer.parseInt(rank);
        }
        return value;
    }
}
public class TestCompare {
    
    public static void main(String[] args) {
    
        Card p = new Card("3","");
        Card q = new Card("3","");
        Card o = p;
        System.out.println(p.compareTo(null));
        System.out.println(p.compareTo(q));
    }
}

Running results :
 Insert picture description here

3、 ... and , About object values greater than 、 be equal to 、 Comparison of less than - Based on comparator

1, know Comparator

public interface Comparator<T> {
      
        //  Return value : 
     // < 0:  Express  o1  The object pointed to is less than  o2  Object to point to  
     // == 0:  Express  o1  The object pointed to is equal to  o2  Object to point to  
     // > 0:  Express  o1  The object pointed to is equal to  o2  Object to point to  
     int compare(T o1, T o2){
    
     //Do
     }
}

2, Code example

import java.util.Comparator;

class Card {
    
    public String rank;  // points 
    public String suit;  // Design and color 

    public Card(String rank, String suit) {
    
        this.rank = rank;
        this.suit = suit;
    }

    public int getValue(){
    
        // In this way String The type becomes an integer number of points 
        int value = 0;
        if("j".equals(rank)){
    
            value =  10;
        } else if("Q".equals(rank)){
    
            value = 11;
        } else if("k".equals(rank)){
    
            value = 12;
        } else if("A".equals(rank)){
    
            value = 14;
        } else {
    
            value = Integer.parseInt(rank);
        }
        return value;
    }
}
class CarComparator implements Comparator<Card> {
    
    @Override
    public int compare(Card o1, Card o2) {
    
        if(o1 == o2){
    
            return 0;
        }
        if(o1 == null){
    
            return -1;
        }
        if(o2 == null){
    
            return 1;
        }
        int result1 = o1.getValue();
        int result2 = o2.getValue();
        return result1-result2;
    }
}
public class TestCompare {
    
    public static void main(String[] args) {
    
        Card p = new Card("3","");
        Card q = new Card("3","");
        Card o = p;
        CarComparator comparator = new CarComparator();
        System.out.println(comparator.compare(p,q));
        System.out.println(comparator.compare(p,null));
        System.out.println(comparator.compare(null,q));
    }
}

Running results :
 Insert picture description here

Four , Compare

 Insert picture description here

5、 ... and , and java Cooperation of collection framework

  1. Use contains Similar approach , The inner part is basically calling the... Of the element equals Method , So the element is required to override equals Method
  2. Use HashMap,key The internal comparison will call equals Method , So the element is required to override equals Method
  3. Use sorting related methods , Internal comparison is needed , So choose to implement Comparable Or introduce a Comparator
  4. Use TreeMap,key Size comparison is required , So choose to implement Comparable Or introduce a Comparator
  5. Other rules are similar

6、 ... and , matters needing attention

1, Use Comparable At the interface , It is best to specify generic parameters . The compiler automatically completes the type verification . If you don't write generic parameters , default compareTo The parameter type of the method is Object type . The program needs to perform type conversion manually .
2, Use Comparable When , You have to make the class to compare implement Comparable Interface . ( You need to modify the code of this class )
3, Use Comparator When , You are re creating a new class implementation Comparator Interface , There is no need to modify the code of the class to be compared

problem : Why have Comparable There needs to be one more Comparato Well ?
1, Use Comparator You have to modify the code with comparison classes , In actual development, not all classes can modify the source code ( This class is provided by libraries or other groups )
2.Comparable Only one comparison rule can be defined ,Comparator You can define a variety of comparison rules

原网站

版权声明
本文为[A goblin]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/177/202206261801123610.html