Details and examples of == and equals of methods in Java

  • 2020-06-23 00:26:37
  • OfStack

Methods == and equals() in Java:

The data types in Java can be divided into two categories:

1. Basic data type, also known as original data type.

byte short, char int, long, float, double, boolean, the comparison between them, the application of the double equal sign (= =), and compare their values.

2. Reference data types (classes)

When they are compared with (==), they are compared with their location in memory, so unless it is an object from the same new, their comparison results in true, or false.

Java among all the classes are inherited from Object the base class, in the base class defines a equals Object () method, the method of the initial behavior is the object of memory address, but this method of 1 some libraries have covered off, such as String Integer, Date among these classes equals has its own implementation, instead of comparing class stored in the heap memory address.

For reference data types, the equals comparison is based on the address value of their location in memory without overwriting the equals method, because the equals method of Object is also compared with the equal sign (==), so the comparison is the same as the equal sign (==).

The equals() method in Object


publicbooleanequals(Objectobj){
return(this==obj);
}
 Here's an example: 
packageorg.java.test;
publicclassPerson{
privateintage;
privateStringname; 
publicintgetAge(){
returnage;
}
publicvoidsetAge(intage){
this.age=age;
}
publicStringgetName(){
returnname;
}
publicvoidsetName(Stringname){
this.name=name;
}
publicPerson(intage,Stringname){
this.age=age;
this.name=name;
}
publicPerson(){
}
@Override
publicinthashCode(){
finalintprime=31;
intresult=1;
result=prime*result+age;
result=prime*result+((name==null)?0:name.hashCode());
returnresult;
}
@Override
publicbooleanequals(Objectobj){
if(this==obj)
returntrue;
if(obj==null)
returnfalse;
if(getClass()!=obj.getClass())
returnfalse;
Personother=(Person)obj;
if(age!=other.age)
returnfalse;
if(name==null){
if(other.name!=null)
returnfalse;
}elseif(!name.equals(other.name))
returnfalse;
returntrue;
} 
}
MainTest.java[java]view plaincopyprint?
packageorg.java.test;
publicclassMainTest{
publicstaticvoidmain(String[]args){
Personp1=newPerson(99,"A");
Personp2=newPerson(99,"A");
Personp3=p1;
System.out.println(p1==p2);//false
System.out.println(p1==p3);//true
System.out.println(p1.equals(p2));
// No overriding equals() Method, return false
// rewrite equals() Method, compares the contents, returns true; 
System.out.println("<====================>");
Strings1="hello";
Strings2="hello";
Strings3=newString("hello");
System.out.println(s1==s2);//true
System.out.println(s1==s3);//false
System.out.println(s1.equals(s2));//true
System.out.println(s1.equals(s3));//true
}
}

I hope this article will be helpful to you


Related articles: