Java‎ > ‎

Object Comparison

By overriding equals() and hashCode functions, one can dictate how two objects are compared and what objects are equal.

package info.compute.example;
import org.apache.commons.lang.builder.HashCodeBuilder;

public class compareObj {
    String objVar;

    public compareObj(String objVar) {
        this.objVar = objVar;
    }

    @Override
    public boolean equals(Object other) {
        if(this.objVar.equals(((compareObj)other).objVar))
            return true;
        else
            return false;
    }

    @Override
    public int hashCode() {
        //17 and 31 are random primes
        return new HashCodeBuilder(17, 31).append(this.objVar).toHashCode();
    }
}



Comments