• Home
  • Space
  • More options


equals(Object obj), compareTo(T obj) and hashCode()

Mandatory synchronization work methods equals (Object obj), compareTo (T obj) and hashCode (). This is their expected behavior and will save you a lot of problems hard to find!
Example:
   
/*   
 * When obj1.equals(obj2)==true then should be obj1.compareTo(obj2)==0 and obj1.hashCode()==obj2.hashCode()
 *
 * hashCode  --> used in hash-based data structures such as HashSet, LinkedHashSet, HashMap, Hashtable
 * equals    --> find element from collection, removing element from collection
 * compareTo --> sort/order collection
 */  
public class Task {
	
	private Long taskId;
	
	public Long getTaskId(){
		return taskId;
	}
	
	@Override
	public int hashCode() {
		return this.taskId.hashCode();
	}
		 
	@Override
	public boolean equals(Object obj) {
		Task other = (Task)obj;
		return this.compareTo(other) == 0;
	}
		
	public int compareTo(Task other) {
		return this.taskId.compareTo(other.getTaskId());
	}
}