[Translation] Using Jakarta Commons to override equals (), hashcode ()

xiaoxiao2021-03-05  28

Jakarta-commons's org.apache.commons.lang.builder package is completely consisting of some classes, which is specifically designed to assist implementation, inheriting some of the basic methods of java.lang.object. For example: equals (), hashcode (), and toString (). They are called builders because they provide a simple set of APIs in order to achieve these methods.

The Equalsbuilder

First discussed EqualsBuilder. This class may have guessed it, it is to help rewrite the equals method of Object.

Let's write a class first:

Public class myclass {

PRIVATE STRING FIELD1;

PRIVATE STRING FIELD2;

Private Double [] Field3;

}

Below we will use EqualsBuilder to process two methods that implement the same class.

Public Boolean Equals (Object O) {

IF (! (instanceof myclass) {

Return False;

}

Myclass rhs = (myclass) O;

Return New Equalsbuilder ()

.appendsuper (Super.Equals (o))

.append (Field1, Rhs.field1)

.append (field2, rhs.field2)

.append (Field3, Rhs.field3)

() .ISEQUALS ();

}

This special builder has not been completely saved from this standard implementation, except for automatic processing of arrays.

In addition, you can also choose a static method using reflex mechanisms:

Public Boolean Equals (Object O) {

Return Equalsbuilder.ReflectionEquals (this, o);

}

This method implements the equals algorithm, there are two shortcomings.

1. Because the reflection mechanism is used, the speed may be slower.

2. In the safe-restricted JVMS, the field modifications in use will result in this method to fail.

However, for rapid development, this is a good tool.

The hashcodebuilder

It is a builder that saves time and avoids mistakes. A HashCode algorithm will be implemented below.

Public Int hashcode () {

Return New Hashcodebuilder (61, 15)

.appendsuper (super.hashcode ())

.append (field1)

.append (Field2)

.append (field3)

.tohashcode ();

}

It looks like Equals builder. Note There are two different numbers in the constructor, and they cannot be zero, and it is odd. These numbers help avoid conflicts, between the various Object's HashCode value.

Alternatively, a method of reflecting mechanisms can also be used.

Public Int hashcode () {

Return hashcodebuilder.reflectionhashcode (this);

}

转载请注明原文地址:https://www.9cbs.com/read-34707.html

New Post(0)