当前位置:网站首页>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
边栏推荐
- 【NPOI】C#跨工作薄复制Sheet模板导出Excel
- next(iter(dataloader))的一点点体会
- Map and list < map > transfer to corresponding objects
- Paging query and join Association query optimization
- Temporarily turn off MySQL cache
- MySQL download and configuration MySQL remote control
- Map and filter methods for processing scarce arrays
- Runtimeerror: CUDA error: out of memory own solution (it is estimated that it is not applicable to most people in special circumstances)
- MYSQL的下载与配置 mysql远程操控
- pycharm的plt.show()如何保持不关闭
猜你喜欢

Get and set settings in 26class

Data Encryption Standard DES security

In and exceptions, count (*) query optimization

Runtimeerror: CUDA error: out of memory own solution (it is estimated that it is not applicable to most people in special circumstances)

带你解决哈希冲突,并实现一个简单hash表,

二分查找-2

Concept and working principle of data encryption standard (DES)

JVM入個門(1)

Vscode usage - Remote SSH configuration description

Let torch cuda. is_ Experience of available() changing from false to true
随机推荐
清华&商汤&上海AI&CUHK提出Siamese Image Modeling,兼具linear probing和密集预测性能!
Data Encryption Standard DES security
#25class的类继承
Connected to surface test questions
请指教同花顺开户选选择哪家券商比较好?现在在线开户安全么?
MYSQL的下载与配置 mysql远程操控
Please advise tonghuashun which securities firm to choose for opening an account? Is it safe to open an account online now?
How about opening a flush account? Is it safe? How to open a stock trading account
Hello, is it safe to open an online stock account and buy stocks now?
idea中文插件chinese(simplified) language pack
数字签名论述及生成与优点分析
我想知道,我在肇庆,到哪里开户比较好?网上开户是否安全么?
让torch.cuda.is_available()从false变成true的一点经验
gdb安装
(必须掌握的多线程知识点)认识线程,创建线程,使用Thread的常见方法及属性,以及线程的状态和状态转移的意义
JS common regular expressions
Chen Qiang: Alibaba's 100 billion level large-scale digital business knowledge map helps business growth
决策树与随机森林
Class inheritance of 25class
RSA concept explanation and tool recommendation - LMN