Showing posts with label Object class. Show all posts
Showing posts with label Object class. Show all posts

Saturday, May 14, 2011

Use of hashcode and equals


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);

}
}

Sunday, May 1, 2011

Why are thread related methods present in Object class

The threading methods are defined in Object class because these methods are related to object locks and any object can act as a lock and hence these methods are defined in the Object class. These methods are wait(), notify() and notifyAll(). These methods are final and return nothing. All of them must be called from a synchronized block or method and the thread calling them should pocess the lock on the object.
While calling wait() method, the thread to release the lock on Object on which wait() method is called and on calling the notify()/notifyAll() makes the other capture the lock.

Chitika