Home > Back-end >  Java - Object. The equals
Java - Object. The equals

Time:10-16

Java - Object. What is the difference between equals method and==? If there is no difference, should be how to generate the difference?

CodePudding user response:

Usually equal representation is the same content,==said is refer to the same,
Such as String s1=new String (" String "); String s2=new String (" String "); The s1. Equals (s2) is true, s1==s2 to false,
If the String s3=s1; The s1. Equals (s3) and s1==s3 are true,
Object class equal is more==directly, so if the custom class, generally is the requirement of rewriting equal method, object class just provide the unified method and content to define your own,

CodePudding user response:

This difference is certainly some simple point is whether comparative content only equals equal and==equal comparative content is also not only will be stored address is equal

CodePudding user response:

This is the Object of the equals method
Public Boolean equals (Object obj) {
Return (this==obj);
}

Want to be rewritten as the difference between, such as String class will rewrite the
Public Boolean equals (Object anObject) {
If (this==anObject) {
return true;
}
If (anObject instanceof String) {
String anotherString=anObject (String);
Int n=value. Length;
If (n==anotherString. Value. Length) {
Char v1 []=value;
Char v2 []=anotherString. Value;
int i=0;
While (n -!=0) {
If (v1 [I]!=v2 [I])
return false;
i++;
}
return true;
}
}
return false;
}

CodePudding user response:

There's a difference,==can only compare the base type, if the object type, the Person object, for example, you have to write their own equals method to compare the object which properties thus considered to be equal

CodePudding user response:

https://blog.csdn.net/qq_35849955/article/details/82988560
  • Related