Using lightweight object comparison

Using lightweight object comparison

  • Using the Apache commons lang can be slow for large scale object comparisons (like sorts) so a faster method is to use something like what is shown below
    Note: All code below should go in the object or object implementation

  1. Create an equals function

    public boolean equals(Object obj) { if (null == obj) return false; if (!(obj instanceof org.sakaiproject.tool.mytool.MyObject)) return false; else { org.sakaiproject.tool.mytool.MyObject castObj = (org.sakaiproject.tool.mytool.MyObject) obj; if (null == this.getId() || null == castObj.getId()) return false; else return (this.getId().equals(castObj.getId())); } }
  2. Create a hashCode function

    public int hashCode() { if (null == this.getId()) return Integer.MIN_VALUE; String hashStr = this.getClass().getName() + ":" + this.getId().hashCode(); return hashStr.hashCode(); }
  3. Create a compareTo function

    public int compareTo(Object obj) { if (obj.hashCode() > hashCode()) return 1; else if (obj.hashCode() < hashCode()) return -1; else return 0; }
  4. Create a toString function

    public String toString() { return super.toString(); }
  5. Your object should now be comparable to objects of the same type that have the same data

    • Safer comparisons should be done using the commons-lang package - Using commons lang for object comparison

    • A sample of an object which demostrates use of the lightweight comparisons: TaskImpl.java

    • A sample of implemented functions using the lightweight method:

      public boolean equals(Object obj) { if (null == obj) return false; if (!(obj instanceof Task)) return false; else { Task castObj = (Task) obj; if (null == this.getId() || null == castObj.getId()) return false; else return (this.getId().equals(castObj.getId())); } } public int hashCode() { if (null == this.getId()) return super.hashCode(); String hashStr = this.getClass().getName() + ":" + this.getId().hashCode(); return hashStr.hashCode(); } public int compareTo(Object obj) { if (obj.hashCode() > hashCode()) return 1; else if (obj.hashCode() < hashCode()) return -1; else return 0; } public String toString() { return super.toString(); }