Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of object comparison in Java

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the Java object comparison example analysis, has a certain reference value, interested friends can refer to the next, I hope you read this article after a lot of gains, the following let Xiaobian take you to understand.

Element comparison Comparison of basic types

In Java, objects of primitive types can be directly sized.

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); } }对象的比较 先来看一段代码 class Card { public int rank; // 数值 public String suit; // 花色 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); //compile successfully---> print false, because c1 and c2 point to different objects //System.out.println(c1

< c2); // 编译报错 System.out.println(c1 == c3); // 编译成功 ---->

Print true because c1 and c3 point to the same object. }}

c1, c2, and c3 are reference variables of Card type, respectively. The above code compares and compiles:

c1 > c2 compilation failed c1== c2 compilation succeeded c1

< c2 编译失败 从编译结果可以看出,Java中引用类型的变量不能直接按照 >

or

< 方式进行比较。 那为什么== 可以比较? 因为:对于用户实现自定义类型,都默认继承自Object类,而Object类中提供了equal方法,而 equal方法 在不覆写的情况下,默认用的就是 ==

The comparison rules for this method are:

Instead of comparing the contents of the object referenced by the reference variable, the address of the reference variable is directly compared

But in some cases, using the equals method to compare does not meet the meaning of the question. We need to overwrite it and modify it to the comparison method we need.

How objects compare

In some cases, what needs to be compared is the content of the object, such as:

When inserting an object into a priority queue, you need to adjust the heap according to the contents of the object. What should you do?

Here are three ways to compare objects

overrides equalpublic class Card { public int rank; //numeric public String suit; //suit public Card(int rank, String suit) { this.rank = rank; this.suit = suit; } @Override public boolean equals(Object o) { //compare yourself to yourself if (this == o) { return true; } // o if null object, or o is not a subclass of Card if (o == null || ! (o instanceof Card)) { return false; }//Note that basic types can be compared directly, but reference types are better to call their equal methods Card c = (Card)o; return rank == c.rank && suit.equals(c.suit); }}

Note: The general pattern of overwriting equals is the one demonstrated above.

Returns true if pointing to the same object

Returns false if null is passed in

Returns false if the object type passed in is not Card

The comparison is done according to the class's achievement goal, for example, if the suit and value are the same, they are considered to be the same card.

Note that calls to comparisons of other reference types also require equals, such as the suit comparison here.

Although the method of overriding the base class equal can be compared, the defect is that equal can only be compared according to equality, and cannot be compared according to greater than or future.

Comparison Based on Comparable Interface Classes

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

For user-defined types, if you want to compare size and manner: when defining the class, implement the Comparble interface, and then override the compareTo method in the class.

public class Card implements Comparable { public int rank; //Value public String suit; //suit public Card(int rank, String suit) { this.rank = rank; this.suit = suit; } //according to numerical comparison, regardless of suit //here we think null is the smallest @Override public int compareTo(Card o) { if (o == null) { return 1; } return rank - o.rank; } public 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, indicates card equality System.out.println(p.compareTo(q)); //

< 0,表示 p 比较小 System.out.println(q.compareTo(p)); // >

0 means q is bigger. }}

Compareble is an interface class in java.lang, which can be used directly.

Comparator-based comparison

Comparator interface source code is as follows:

Compare according to the comparator mode, the specific steps are as follows:

User-defined comparator class to implement Comparator interface

class CardComparator implements Comparator { //according to numerical comparison, regardless of suit //here we think null is the smallest ******************** //overwrite code area ********************}

Note: Distinguish between Comparable and Comparator.

Overwrite the compare method in Comparator

@Override public int compare(Card o1, Card o2) { if (o1 == o2) { return 0; } if (o1 == null) { return -1; } if (o2 == null) { return 1; } return o1.rank - o2.rank; }

Calling custom comparators

public static void main(String[] args){ Card p = new Card(1, "♠"); Card q = new Card(2, "♠"); Card o = new Card(1, ""); //Defines the comparator object CardComparator cmptor = new CardComparator(); //Compare using comparator objects System.out.println(cmptor.compare (p, o)); // == 0, indicating card equality System.out.println(cmptor.compare(p, q)); //

< 0,表示 p 比较小 System.out.println(cmptor.compare(q, p)); // >

0 means q is bigger. }

Note: Comparator is a generic interface class in java.util package, which must be imported when used.

Comparison of three comparison methods

Overwrite method description Object. equalsBecause all classes are inherited from Object, so directly override can be, but can only compare equality or not Comparable.compareTo requires manual implementation of the interface, more intrusive, but once implemented, each time using the class has an order, belongs to the internal order Comparator.compare needs to implement a comparator object, treat the comparison class less intrusive, but the algorithm code to achieve intrusive PriorityQueue(Priority Queue) comparison method in the collection framework

PriorityQueue in the collection framework uses heap structure at the bottom, so its internal elements must be able to compare size. PriorityQueue adopts two methods: Comparble and Comparator.

Comparable is the default internal comparison method. If the user inserts a custom type object, the object must implement the Comparable interface and override the compareTo method.

Users can also choose to use comparator objects. If users insert custom type objects, they must provide a comparator class that implements the Comparator interface and overrides the compare method.

Thank you for reading this article carefully. I hope that the article "Example Analysis of Object Comparison in Java" shared by Xiaobian will be helpful to everyone. At the same time, I hope that everyone will support it a lot and pay attention to the industry information channel. More relevant knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report