当前位置:网站首页>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
边栏推荐
- Please advise tonghuashun which securities firm to choose for opening an account? Is it safe to open an account online now?
- Preparing for the Blue Bridge Cup and ccf-csp
- RSA加密解密详解
- 深层次安全定义剖析及加密技术
- Paging query and join Association query optimization
- Prometeus 2.34.0 new features
- MySQL的MVCC机制详解
- 比较两个对象的大小关系原来可以如此花里胡哨
- JS common regular expressions
- 数字签名标准(DSS)
猜你喜欢

行锁与隔离级别案例分析

vutils.make_grid()与黑白图像有关的一个小体会

Lm06 the mystery of constructing the bottom and top trading strategy only by trading volume

MYSQL的下载与配置 mysql远程操控

VCD-影音光碟

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

IDEA收藏代码、快速打开favorites收藏窗口

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

贝叶斯网络详解
![[buuctf.reverse] 126-130](/img/df/e35633d85caeff1dece62a66cb7804.png)
[buuctf.reverse] 126-130
随机推荐
贝叶斯网络详解
行锁分析和死锁
Solve the problem that each letter occupies a space in pycharm
利用递归实现求n位所有格雷码
Detailed explanation of dos and attack methods
Decision tree and random forest
JVM入個門(1)
非对称密码体制详解
数据加密标准DES安全性
Discussion and generation of digital signature and analysis of its advantages
pycharm如何修改多行注释快捷键
图像二值化处理
Properties file garbled
你好,现在网上股票开户买股票安全吗?
Applet setting button sharing function
VCD video disc
CD-CompactDisk
同花顺开户怎么样安全吗?怎么炒股开户
陈强:阿里千亿级大规模数字商业知识图谱助力业务增长
[npoi] C copy sheet template across workbooks to export Excel