当前位置:网站首页>Do you know how to compare two objects
Do you know how to compare two objects
2022-06-26 18:10:00 【A goblin】
List of articles
- One , Comparison of equal object values
- Two , About object values greater than 、 be equal to 、 Comparison of less than - Based on natural order
- 3、 ... and , About object values greater than 、 be equal to 、 Comparison of less than - Based on comparator
- Four , Compare
- 5、 ... and , and java Cooperation of collection framework
- 6、 ... and , matters needing attention
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 :
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
}
}
Be careful : General override equals The routine is demonstrated above
- If you point to the same object , return true
- If the incoming is null, return false
- If the object type passed in is not Card, return false
- 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
- 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 :
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 :
Four , Compare

5、 ... and , and java Cooperation of collection framework
- 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
- Use HashMap,key The internal comparison will call equals Method , So the element is required to override equals Method
- Use sorting related methods , Internal comparison is needed , So choose to implement Comparable Or introduce a Comparator
- Use TreeMap,key Size comparison is required , So choose to implement Comparable Or introduce a Comparator
- 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
边栏推荐
- DoS及攻击方法详解
- Introduction to Ethereum Technology Architecture
- Detailed explanation of asymmetric cryptosystem
- 腾讯钱智明:信息流业务中的预训练方法探索与应用实践
- properties文件乱码
- Map and filter methods for processing scarce arrays
- JVM entry Door (1)
- Li Kou daily question - day 28 -566 Reshape matrix
- SQL中的并、交、差运算
- vutils. make_ A little experience of grid () in relation to black and white images
猜你喜欢

Dos et détails de la méthode d'attaque

tag动态规划-刷题预备知识-2. 0-1背包理论基础和二维数组解法模板

二分查找-2

properties文件乱码

CLion断点单步调试

Tsinghua & Shangtang & Shanghai AI & CUHK proposed Siamese image modeling, which has both linear probing and intensive prediction performance!

Analysis of deep security definition and encryption technology

Ethereum技术架构介绍

清华&商汤&上海AI&CUHK提出Siamese Image Modeling,兼具linear probing和密集预测性能!

Applet setting button sharing function
随机推荐
JVM入個門(1)
RuntimeError: CUDA error: out of memory自己的解决方法(情况比较特殊估计对大部分人不适用)
ROS查询话题具体内容常用指令
js强制转换
无需人工先验!港大&同济&LunarAI&旷视提出基于语义分组的自监督视觉表征学习,显著提升目标检测、实例分割和语义分割任务!
wechat_ Solve the problem of page Jump and parameter transfer by navigator in wechat applet
ROS的发布消息Publishers和订阅消息Subscribers
VCD-影音光碟
DoS及攻击方法详解
RSA concept explanation and tool recommendation - LMN
pycharm如何修改多行注释快捷键
9、智慧交通项目(2)
Binary search-1
行锁与隔离级别案例分析
Case study of row lock and isolation level
比较两个对象的大小关系原来可以如此花里胡哨
利用递归实现求n位所有格雷码
[unity] use C in unity to execute external files, such as Exe or bat
深层次安全定义剖析及加密技术
map和filter方法对于稀缺数组的处理