search
HomeJavajavaTutorialequals() in Java

equals() in Java

Dec 16, 2016 am 09:13 AM
equals

After several days of study, I finally have a more comprehensive understanding of the usage of equals and make a summary.

1. The original meaning of equals - that is, what is the meaning of the equals() method defined in the Object object.

(The function of == is attached here first, and there will be a description later. Because the relationship between == and the equals() method is very close, I will have my own opinions later.

== is used to compare references and comparisons Basic data types have different functions:
Comparing basic data types, if the two values ​​are the same, the result is true
And when comparing references, if the reference points to the same object in memory, the result is true)

public boolean equals(Object obj)

The comparison rule is: when the object referenced by parameter obj is the same object as the current object, it returns true, otherwise it returns false.

public class Fish {
private int weight;
private String color;

public Fish(int weight, String color) {
this.color = color;
this.weight = weight;
}

public int getWeight() {
return weight;
}

public void setWeight(int weight) {
This.weight = weight;
}

public String getColor() {
return color;
}

public void setColor(String color) {
this.color = color ;
}

}

public class EqualsTest {
public static void main(String[] args) {
Fish f1 = new Fish(1, "blue");
Fish f2 = new Fish(1, "blue");

        System.out.println(f1 == f2);
    System.out.println(f1.equals(f2));
  }
}

——————The running result is—————— —

false
false

It can be seen that the original intention of the equals() method is to determine whether the references of two objects are the same.

2. There are some classes in the JDK class that cover the equals() method of the object class. The comparison rule is: if the two objects have the same type and the same content, true will be returned. These classes are:
java.io. file,java.util.Date,java.lang.string, wrapper class (Integer, Double, etc.)

public class EqualsTest {
public static void main(String[] args) {
String s1=new String("sss" ); T String S2 = New String ("SSS");

System.out.println (s1 == S2);
System.out.println (s1.equals (s2)); ————————The operation result is——————

false
true

From this we know that the equals() method in String has been overwritten, so that its meaning becomes the comparison of the contents of two objects. Is it consistent

3. If we want to override the equals() method ourselves, let it compare the content or have other methods of use (of course we usually use it to compare the content, but what is the real implementation of the overridden method? Yes, who knows? O(∩_∩)O~)

public class Fish {

private int weight;

private String color;

    public Fish(int weight, String color) {
        this.color = color;
        this.weight = weight;
    }
    
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((color == null) ? 0 : color.hashCode());
        result = prime * result + weight;
        return result;
    }
    
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Fish other = (Fish) obj;
        if (color == null) {
            if (other.color != null)
                return false;
        } else if (!color.equals(other.color))
            return false;
        if (weight != other.weight)
            return false;
        return true;
    }
    public int getWeight() {
        return weight;
    }

    public void setWeight(int weight) {
        this.weight = weight;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

}

public class EqualsTest {
    public static void main(String[] args) {
        Fish f1 = new Fish(1, "blue");
        Fish f2 = new Fish(1, "blue");

 

        System.out.println(f1 == f2);
        System.out.println(f1.equals(f2));
    }
}

——————运行结果为——————

false
true

此例子中我复写了equals()方法和hashcode()方法,使得equals()方法脱离的本意,不再是比较两个对象的引用是否相同,而是比较其内容是否相同。

以上内容为一般书上的总结,下面是我自己想到的一些东西。

我们可以知道计算机归根到底进行的只是一些二进制数的与或非运算,加法乘法运算。由此有了些基本的运算符,所有的函数本质上其实现都是使用基本运算符来实现的。而==是基本运算符中的一个,它的作用:用于比较引用和比较基本数据类型时具有不同的功能:
     比较基本数据类型,如果两个值相同,则结果为true
     而在比较引用时,如果引用指向内存中的同一对象,结果为true

而equals()作为方法,我们可以推测知道,它其中的实现所使用的肯定是==运算符。再进一步的思考,equals()本意不正是==运算符进行对象比较时候的作用吗。那么,既然是两者有同样的作用,为什么还要弄出一个equals()方法来呢。因为==运算符不允许我们进行覆盖,也就是说它限制了我们的表达。在上面的第三个例子中,我们复写equals()方法,达到比较对象内容是否相同的目的。而这些通过==运算符是做不到的。




更多Java中的equals()相关文章请关注PHP中文网!


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JVM performance vs other languagesJVM performance vs other languagesMay 14, 2025 am 12:16 AM

JVM'sperformanceiscompetitivewithotherruntimes,offeringabalanceofspeed,safety,andproductivity.1)JVMusesJITcompilationfordynamicoptimizations.2)C offersnativeperformancebutlacksJVM'ssafetyfeatures.3)Pythonisslowerbuteasiertouse.4)JavaScript'sJITisles

Java Platform Independence: Examples of useJava Platform Independence: Examples of useMay 14, 2025 am 12:14 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunonanyplatformwithaJVM.1)Codeiscompiledintobytecode,notmachine-specificcode.2)BytecodeisinterpretedbytheJVM,enablingcross-platformexecution.3)Developersshouldtestacross

JVM Architecture: A Deep Dive into the Java Virtual MachineJVM Architecture: A Deep Dive into the Java Virtual MachineMay 14, 2025 am 12:12 AM

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVM: Is JVM related to the OS?JVM: Is JVM related to the OS?May 14, 2025 am 12:11 AM

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceJava: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceMay 14, 2025 am 12:05 AM

Java implementation "write once, run everywhere" is compiled into bytecode and run on a Java virtual machine (JVM). 1) Write Java code and compile it into bytecode. 2) Bytecode runs on any platform with JVM installed. 3) Use Java native interface (JNI) to handle platform-specific functions. Despite challenges such as JVM consistency and the use of platform-specific libraries, WORA greatly improves development efficiency and deployment flexibility.

Java Platform Independence: Compatibility with different OSJava Platform Independence: Compatibility with different OSMay 13, 2025 am 12:11 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

What features make java still powerfulWhat features make java still powerfulMay 13, 2025 am 12:05 AM

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

Top Java Features: A Comprehensive Guide for DevelopersTop Java Features: A Comprehensive Guide for DevelopersMay 13, 2025 am 12:04 AM

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor