Clean Java

There is always a bigger game

Multiple attributes to compare objects.

with one comment

There would be cases you would want use a second attribute to compare two objects of same type if the first attribute comparison is not good enough. In the compareTo method you can choose to go a second attribute to compare two objects of same type. Here is a simple example where the compareTo method used the lastName to compare two objects of Employee if the firstName of two employee objects are same.


package org.sanju;

/**
 *
 * @author sanju.org
 *
 * Multiple attributes to compare Objects.
 * Multiple attributes in cmpareTo method.
 *
 */

public class Employee implements Comparable<Employee> {

	private Name name;

	class Name{
		private String firstName;
		private String lastName;
	}

	public int compareTo(Employee o) {
		if(this.name.firstName.compareTo(o.name.firstName) == 0){
			return this.name.lastName.compareTo(o.name.lastName);
		}
		return this.name.firstName.compareTo(o.name.firstName);
	}
}

Advertisements

One Response

Subscribe to comments with RSS.

  1. When implementing compareTo() method, keep in mind the following, so that Tree based collections works properly.
    ———-
    The natural ordering for a class C is said to be consistent with equals if and only if (e1.compareTo((Object)e2) == 0) has the same boolean value as e1.equals((Object)e2) for every e1 and e2 of class C. Note that null is not an instance of any class, and e.compareTo(null) should throw a NullPointerException even though e.equals(null) returns false.

    It is strongly recommended (though not required) that natural orderings be consistent with equals. This is so because sorted sets (and sorted maps) without explicit comparators behave “strangely” when they are used with elements (or keys) whose natural ordering is inconsistent with equals. In particular, such a sorted set (or sorted map) violates the general contract for set (or map), which is defined in terms of the equals method.
    –(Extract from Java API)

    manchikantir

    March 22, 2012 at 7:03 am


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: