GeoTools

OSGeo

Previous topic

ObjectCache

Next topic

Metadata

This Page

UtilitiesΒΆ

The Utilities class is interesting, in that it contains helper methods used when implementing basic Java functionality such as equals or hashcode.

  • It is fairly annoying to compare if two objects are equal, when either of the objects could be null.
  • It is also annoying to sort out how to compare or print an array

Here is what Utilities offers:

    
    // equals provides a null safe equals check
    Utilities.equals(string1, string2); // null safe equals check
    Utilities.equals(null, "Hello"); // false
    Utilities.equals(null, null); // true!
    
    // deepEquals will check the contents of arrays
    Utilities.deepEquals(new double[] { 1.0 }, new double[] { 1.0 });
    
    // deepToString will print out objects and arrays
    Utilities.deepToString(new double[] { 1.0, Math.PI, Math.E });
    
    // when implementing your own object the following are handy
    Utilities.hash(value, seed);
    Utilities.equals(value, object);
    Utilities.ensureNonNull("parameter", object);

Several of the other methods are useful when you are implementing your own Object.

Here is an example:

package org.geotools.metadata;

import org.geotools.util.Utilities;

public class Example {
    
    private Object field1;
    private int field2;
    private double array[];
    
    @Override
    public int hashCode() {
        int result = 1;
        result = Utilities.hash(field1, result);
        result = Utilities.hash(field2, result);
        result = Utilities.hash(array, result);
        
        return result;
    }
    
    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (!(obj instanceof Example)) {
            return false;
        }
        Example other = (Example) obj;
        return Utilities.equals(field1, other.field1) && Utilities.equals(field2, other.field2)
                && Utilities.deepEquals(array, other.array);
    }
    
    @Override
    public String toString() {
        StringBuilder build = new StringBuilder();
        build.append("Example[");
        if (field1 != null) {
            build.append(" field1=");
            build.append(field1);
        }
        build.append(" field2=");
        build.append(field2);
        if (array != null) {
            build.append(" array=");
            build.append(Utilities.deepToString(array));
        }
        build.append("]");
        return build.toString();
    }
}