1. Why does the equals() method need to be rewritten?
Determine whether two objects are logically equal, such as judging whether instances of two classes are equal based on the member variables of the class. However, the equals method in inherited Object can only determine whether two reference variables are the same object. In this way we often need to override the equals() method.
When we add elements to a collection without duplicate objects, objects are often stored in the collection. We need to first determine whether there are known objects in the collection, so we must override the equals method.
2. How to rewrite the equals() method?
Requirements for overriding the equals method:
1. Reflexivity: x.equals(x) should return true for any non-null reference x.
2. Symmetry: For any reference to x and y, if x.equals(y) returns true, then y.equals(x) should also return true.
3. Transitivity: For any reference x, y and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should also return true.
4. Consistency: If the objects referenced by x and y have not changed, then calling x.equals(y) repeatedly should return the same result.
5. Non-nullability: For any non-null reference x, x.equals(null) should return false.
Format:
Java code
public boolean equals(Object obj) { if(this == obj) return false; if(obj == null) return false; if(getClass() != obj.getClass() ) return false; MyClass other = (MyClass)obj; if(str1 == null) { if(obj.str1 != null) { return false; } }else if (!str1.equals(other.str1) ) return false; } if(var1 != other.var1) return false; return true; }
If new features are added to the subclass while retaining the equals method, it will be more complicated.
Next, let’s understand the above agreement through examples. We first start with a simple non-mutable two-dimensional point class:
public class Point{ private final int x; private final int y; public Point(int x, int y){ this.x = x; this.y = y; } public boolean equals(Object o){ if(!(o instanceof Point)) return false; Point p = (Point)o; return p.x == x && p.y == y; } }
Suppose you want to extend this class to add color information to a point:
public class ColorPoint extends Point{ private Color color; public ColorPoint(int x, int y, Color color){ super(x, y); this.color = color; } //override equasl() public boolean equals(Object o){ if(!(o instanceof ColorPoint)) return false; ColorPoint cp = (ColorPoint)o; return super.equals(o) && cp.color==color; } }
We override the equals method, only if It returns true only when the actual parameter is another colored point with the same position and color. But the problem with this method is that when you compare a normal point with a colored point, and vice versa, you may get different results:
public static void main(String[] args){ Point p = new Point(1, 2); ColorPoint cp = new ColorPoint(1, 2, Color.RED); System.out.println(p.equals(cp)); System.out.println(cp.eqauls(p)); }
Running results:
true
false
Such a result obviously violates To correct the symmetry, you can try this to correct this problem: let ColorPoint.equals ignore color information when performing "mixed comparisons":
public boolean equals(Object o){ if(!(o instanceof Point)) return false; //如果o是一个普通点,就忽略颜色信息 if(!(o instanceof ColorPoint)) return o.equals(this); //如果o是一个有色点,就做完整的比较 ColorPoint cp = (ColorPoint)o; return super.equals(o) && cp.color==color; }
What will be the result of this method? Let’s test it first:
public static void main(String[] args){ ColorPoint p1 = new ColorPoint(1, 2, Color.RED); Point p2 = new Point(1, 2); ColorPoint p3 = new ColorPoint(1, 2, Color.BLUE); System.out.println(p1.equals(p2)); System.out.println(p2.equals(p1)); System.out.println(p2.equals(p3)); System.out.println(p1.eqauls(p3)); }
Running result:
true
true
true
false
This method does provide symmetry, but it sacrifices transitivity (by convention, p1.equals(p2) and p2.equauals(p3) all returns true, p1.equals(p3) should also return true). How to solve it?
In fact, this is a basic question about equivalence relations in object-oriented languages. There is no easy way to extend an instantiable class to add new features while retaining the equals convention. The new solution is to no longer let ColorPoint extend Point, but to add a private Point field and a public view method to ColorPoint:
public class ColorPoint{ private Point point; private Color color; public ColorPoint(int x, int y, Color color){ point = new Point(x, y); this.color = color; } //返回一个与该有色点在同一位置上的普通Point对象 public Point asPoint(){ return point; } public boolean equals(Object o){ if(o == this) return true; if(!(o instanceof ColorPoint)) return false; ColorPoint cp = (ColorPoint)o; return cp.point.equals(point)&& cp.color.equals(color); } }
Another solution is to design Point as An abstract class so that you can add new features to subclasses of the abstract class without violating the equals contract. Because abstract classes cannot create instances of the class, none of the problems mentioned above will occur.
Key points of overriding the equals method:
1. Use the == operator to check "whether the actual parameter is a reference to the object".
2. Determine whether the actual parameter is null
3. Use the instanceof operator to check "whether the actual parameter is of the correct type".
4. Convert the actual parameters to the correct type.
5. For each "key" field in this class, check whether the field in the actual parameter matches the corresponding field value in the current object.
For fields of basic types that are neither float nor double, you can use the == operator for comparison; for fields of object reference types, you can call the equals method of the referenced object recursively; for fields of float type, First use Float.floatToIntBits to convert to an int type value, and then use the == operator to compare the int type value; for double type fields, first use Double.doubleToLongBits to convert to a long type value, and then use the == operator Compares values of type long.
6. After you write the equals method, you should ask yourself three questions: Is it symmetric, transitive, and consistent? (The other two characteristics will usually be satisfied by themselves) If the answer is no, then please find the reason why these characteristics are not satisfied, and then modify the code of the equals method.

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

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

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.

JavaisnotentirelyplatformindependentduetoJVMvariationsandnativecodeintegration,butitlargelyupholdsitsWORApromise.1)JavacompilestobytecoderunbytheJVM,allowingcross-platformexecution.2)However,eachplatformrequiresaspecificJVM,anddifferencesinJVMimpleme

TheJavaVirtualMachine(JVM)isanabstractcomputingmachinecrucialforJavaexecutionasitrunsJavabytecode,enablingthe"writeonce,runanywhere"capability.TheJVM'skeycomponentsinclude:1)ClassLoader,whichloads,links,andinitializesclasses;2)RuntimeDataAr

Javaremainsagoodlanguageduetoitscontinuousevolutionandrobustecosystem.1)Lambdaexpressionsenhancecodereadabilityandenablefunctionalprogramming.2)Streamsallowforefficientdataprocessing,particularlywithlargedatasets.3)ThemodularsystemintroducedinJava9im

Javaisgreatduetoitsplatformindependence,robustOOPsupport,extensivelibraries,andstrongcommunity.1)PlatformindependenceviaJVMallowscodetorunonvariousplatforms.2)OOPfeatureslikeencapsulation,inheritance,andpolymorphismenablemodularandscalablecode.3)Rich

The five major features of Java are polymorphism, Lambda expressions, StreamsAPI, generics and exception handling. 1. Polymorphism allows objects of different classes to be used as objects of common base classes. 2. Lambda expressions make the code more concise, especially suitable for handling collections and streams. 3.StreamsAPI efficiently processes large data sets and supports declarative operations. 4. Generics provide type safety and reusability, and type errors are caught during compilation. 5. Exception handling helps handle errors elegantly and write reliable software.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

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.

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.
