The difference between equals() and == (Java)
"==" usage
- Basic data type: the double equal sign compares the value
- Reference data type: the double equal sign compares the address in memory
equals() usage
- Did not override the equals() method: compare addresses in memory
- Override the equals() method: refer to the overridden method
The class that rewrites the equals() method:
String:
The rewritten equals() method compares the contents of the string;
All string judgments use the equals() method, and the double equal sign is judged based on the memory address.
Use == when judging whether a string is null, and compare the length when judging whether it is an empty string eg. string.length()!=0
Integer:
The rewritten equals() method compares the value of the integer variable;
Note: When assigning a value to an Integer object, the value between -128 and 127 will be cached in IntegerCache.cache, so when assigning a value between -128 and 127 to an Integer object, the same object will be returned. In this case, double The equal sign and equals() method comparison are both true
The Java auto-boxing specification requires boolean, byte, char<=127, and short and int between -128~127 are packed into fixed objects.
Note: The comparison of values between all packaging objects of the same type are all compared using the equals() method.
Enumeration class:
eg:
public enum Size {
SMALL,MEDIUM,LARGE,EXTRA_LARGE};
The type defined by this declaration is actually a class, which happens to have 4 instances. When comparing the values of two enumeration types, you never need to call equals, just call "==" directly.
Class object (reflection):
The virtual machine manages a Class object for each type, so the == operator can be used to compare two class objects, eg:
Employee e = new Employee();
if(e.getClass()==Employee.class){
}
Update after discovering new #_#