search
HomeJavajavaTutorialSummary and sharing of three ways to compare the sizes of two objects in Java

This article brings you relevant knowledge about java. The elements inserted in the priority queue must be comparable in size. If the size cannot be compared, such as inserting two student type elements, A ClassCastException exception will be reported. The following introduces three methods for comparing the sizes of two objects in Java. I hope it will be helpful to everyone.

Summary and sharing of three ways to compare the sizes of two objects in Java

Recommended study: "java video tutorial"

1. Why comparison objects are needed

Previous section The priority queue is introduced. The elements inserted in the priority queue must be comparable in size. If the size cannot be compared, such as inserting two student type elements, a ClassCastException will be reported.

Example:

class Student{
    String name;
    int age;
 
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
}
public class Test {
    public static void main(String[] args) {
        Student s1 = new Student("张三",25);
        Student s2 = new Student("李四",31);
        PriorityQueue<Student> p = new PriorityQueue<>();
        p.offer(s1);
        p.offer(s2);
    }
}

Result:

Cause: Because the bottom layer of the priority queue uses a heap data structure, when inserting elements into the heap, elements need to be compared, and Student has no way Direct comparison, so an exception is thrown

2. Comparison of elements

1. Comparison of basic types

In Java, elements of basic types can be compared directly

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 = &#39;a&#39;;
        char c2 = &#39;b&#39;;
        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);
    }
}

2. Comparison of reference types

class Student{
    String name;
    int age;
 
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
}
public class Test {
    public static void main(String[] args) {
        Student s1 = new Student("张三",25);
        Student s2 = new Student("李四",31);
        Student s3 = s1;
        System.out.println(s1==s2);  //false
        System.out.println(s1==s3);  //true
        //System.out.println(s1<s2); 编译报错
        //System.out.println(s1>s3); 编译报错
    }
}

Judging from the above results, custom types cannot be compared using >, <. why can they be compared using="=?">

==When comparing custom types, what is compared is whether the addresses of the objects are the same

But we often need to compare the contents of the objects, such as inserting an object into the priority queue, you need to follow The content of the object is used to adjust the heap, so how to compare?

3. Object comparison methods

1. equals method comparison

The Object class is the base class of each class, which provides the equals() method to compare content Are they the same

#But the equals method in Object uses == to compare by default, which is to compare the addresses of two objects, so I want to make custom types comparable, You can override the equals() method of the base class

Example:

class Student{
    String name;
    int age;
 
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
 
    @Override
    public boolean equals(Object obj) {
        if(this == obj){
            return true;
        }
        if(obj==null || !(obj instanceof Student)){
            return false;
        }
        Student s = (Student) obj;
        return this.age==s.age && this.name.equals(s.name);
    }
}
public class Test {
    public static void main(String[] args) {
        Student s1 = new Student("张三",25);
        Student s2 = new Student("李四",31);
        Student s3 = new Student("李四",31);
        System.out.println(s1.equals(s2));
        System.out.println(s2.equals(s3));
    }
}

Result: You can compare whether the contents are the same

Steps to override the equals method

  • If the addresses of the two objects are the same, return true
  • If the incoming object is null, return false
  • If the incoming object and the calling object are not of the same type, return false
  • If the contents are the same, return true, otherwise return false

Notes

The equals() method can only compare whether two objects are the same, and cannot compare according to >,

2. Comparison based on the Comparable interface

For reference types, if you want to compare based on size, implement the Comparable interface when defining the class, and then override the compareTo method in the class

Example: Compare the size of two people, usually based on age

class Person implements Comparable<Person>{
    String name;
    int age;
 
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
 
    @Override
    public int compareTo(Person o) {
        if(o == null){
            return 1;
        }
        return this.age-o.age;
    }
}
public class Test1 {
    public static void main(String[] args) {
        Person p1 = new Person("小王",22);
        Person p2 = new Person("小张",21);
        Person p3 = new Person("小方",22);
        System.out.println(p1.compareTo(p2)); //>0表示大于
        System.out.println(p2.compareTo(p3)); //<0表示小于
        System.out.println(p1.compareTo(p3)); //==0表示相等
    }
}

The compareTo method is an interface class in java.lang and can be used directly

Using the Comparable interface allows objects of type Student to be inserted into the priority queue

import java.util.PriorityQueue;
 
class Student implements Comparable<Student> {
    String name;
    int age;
 
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
 
    @Override
    public int compareTo(Student o) {
        if(o == null){
            return -1;
        }
        return this.age-o.age;
    }
}
public class Test {
    public static void main(String[] args) {
        Student s1 = new Student("张三",25);
        Student s2 = new Student("李四",31);
        Student s3 = new Student("李四",35);
        PriorityQueue<Student> p = new PriorityQueue<>();
        p.offer(s1);
        p.offer(s2);
        p.offer(s3);
    }
}

Result: Student Type objects can also be inserted into the priority queue

3. Comparison based on the Comparator interface

The specific steps for comparison according to the comparator are as follows:

  • Create a comparator class and implement the Comparator interface
  • Override the compare method

Use the comparator so that Student type objects can be inserted into the priority queue

import java.util.Comparator;
import java.util.PriorityQueue;
 
class Student {
    String name;
    int age;
 
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
}
class StudentComparator implements Comparator<Student>{
    @Override
    public int compare(Student o1, Student o2) {
        if(o1 == o2){
            return 0;
        }
        if(o1 == null){
            return -1;
        }
        if(o2 == null){
            return 1;
        }
        return o1.age-o2.age;
    }
}
public class Test {
    public static void main(String[] args) {
        Student s1 = new Student("张三",25);
        Student s2 = new Student("李四",31);
        Student s3 = new Student("李四",35);
        PriorityQueue<Student> p = new PriorityQueue<>(new StudentComparator());
        p.offer(s1);
        p.offer(s2);
        p.offer(s3);
    }
}

Result: Student type objects can be inserted into the priority queue

Comparator is a generic interface class in the java.util package. It must be used Import the corresponding package

4. Three comparison methods

Rewriting method Explanation
Object.equals Can only compare whether the contents of two objects are equal, not the size
Comparable.compareTo Class To implement the interface, it is highly intrusive to the class and destroys the structure of the original class
Comparator.compare It is necessary to implement a comparator class, which is intrusive to the class Weak, does not destroy the original class

Comparable, what comparison method does Comparator use?

If we get a class defined by others, we cannot operate on the class, so we can use the method of creating a class to implement the Comparator interface

If the class is a class defined by the user, we can operate on the class To operate, use the method of implementing the Comparable interface

Recommended learning: "java video tutorial"

The above is the detailed content of Summary and sharing of three ways to compare the sizes of two objects in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:脚本之家. If there is any infringement, please contact admin@php.cn delete
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.