Showing posts with label commons-lang. Show all posts
Showing posts with label commons-lang. Show all posts

Sunday, 15 May 2011

Implementing compareTo() using commons-lang

Here CompareToBuilder is used to implement compareTo();

public int compareTo(Person person) {
return new CompareToBuilder()
append(this.firstName, person.firstName)
append(this.lastName, person.firstName)
toComparison();
}


Also, there is yet another reflection option:


public int compareTo(Object o) {
return CompareToBuilder.reflectionCompare(this, o);
}

Saturday, 14 May 2011

Implementing hashCode using commons-lang

This example shows how to implement hashCode() using HashCodeBuilder of commons-lang.

import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.EqualsBuilder;

import java.io.Serializable;

public class MyClass implements Serializable {
private Long id;

private String title;

private String author;

public int hashCode() {
return new HashCodeBuilder().append(id).append(title).append(author).toHashCode();

// return HashCodeBuilder.reflectionHashCode(this);

}
}

 

Also, reflection can be used to implement the same function:


public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}


Implement equals method using commons-lang

Here we use EqualsBuilder to see whether the 2 objects are equal or not. Take the example of person:

import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.EqualsBuilder;

import java.io.Serializable;

public class Person implements Serializable {
private Long id;

private String name;

private String sirname;

public boolean equals(Object object) {
if (!(object instanceof Main)) {
return false;
}

if (object == this) {
return true;
}

Person person = (Person) object;
return new EqualsBuilder().append(this.id, person.id).append(this.name, person.name)
.append(this.sirname, person.sirname).isEquals();

// return EqualsBuilder.reflectionEquals(this, person);

}
}