Skip to content

equal_hashcode_tostring

Green Luo edited this page Jan 15, 2016 · 3 revisions

The three essential methods associated with Object class are boolean equals(Object), int hashCode(), String toString(). Every Java developer should be aware of the importance of these methods especially the former two. If you don't know then you should read this book by Joshua Bloch.

OSGL Tool provides tool to save your time writing/using these methods

boolean $.eq(Object, Object)

The benefit of $.eq() utility is about the null handling:

Old way

if (o1 == o2 || o1 != null && o1.equals(o2)) {
    // do something
}

New way

if ($.eq(o1, o2)) {
    // do something
}

$.eq variants

boolean $.ne(Object, Object)

This is an expressive way for negate $.eq, so instead of writing

if (!$.eq(o1, o2)) {...}

You can write more readable

if ($.ne(o1, o2)) {...}

boolean $.eq2(Object, Object)

If your objects are arrays, then you should use $.eq2(Object, Object) method which allows comparing the array elements

int $.hc(...)

Tool to make generating hash code easily. Suppose you have a Contact class with the following fields:

public class Contact {
    private String firstName;
    private String lastName;
    private Address addr1;
    private Address addr2;
    private String mobile;
    private String phone;
}

Now we need to implement the hashCode() method for Contact class. Here is the old way to go:

@Override
public int hashCode() {
    int hc = 17;
    if (null != firstName) {
        hc = 31 * hc + firstName.hashCode();
    }
    if (null != lastName) {
        hc = 31 * hc + lastName.hashCode();
    }
    if (null != addr1) {
        hc = 31 * hc + addr1.hashCode();
    }
    if (null != addr2) {
        hc = 31 * hc + addr2.hashCode();
    }
    if (null != mobile) {
        hc = 31 * hc + mobile.hashCode();
    }
    if (null != phone) {
        hc = 31 * hc + phone.hashCode();
    }
    return hc;
}

With $.hc you do the same thing in a very expressive way:

@Override
public int hashCode() {
    return $.hc(firstName, lastName, addr1, addr2, mobile, phone);
}

Note An additional benefit is you don't need to worry about arrays, $.hc() handles array greatly

String $.toString(Object)

The simple thing about $.toString(Object) is null value handling. Instead of doing something like:

String s = null == obj ? "" : obj.toString();

You go with:

String s = $.toString(obj);

$.toString(Object) Variants

$.toString2(Object)

This method should be used when Object might be array