Important alert: (current site time 7/15/2013 2:49:04 PM EDT)
 

VB icon

A simple universal comparator

Email
Submitted on: 11/29/2002 9:22:22 PM
By: Lone Deranger 
Level: Advanced
User Rating: By 2 Users
Compatibility: Java (JDK 1.1), Java (JDK 1.2)
Views: 23195
 
     You can use this class to sort an array of Objects without creating custom Comparators for each field. For example, if you have a class Employee, with methods getName() and getSalary(), you can simply do Arrays.sort(myEmployeeArray, new UniversalComparator("getName", 1)) or Arrays.sort(myEmployeeArray, new UniversalComparator("getSalary", -1)). The first statement would sort your array in ascending order by the value of getName() method, the second would sort it in descending order by the value of getSalary() method. The class uses the reflection API to accomplish this task.
 
code:
Can't Copy and Paste this?
Click here for a copy-and-paste friendly version of this code!
 
Terms of Agreement:   
By using this code, you agree to the following terms...   
  1. You may use this code in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.
  2. You MAY NOT redistribute this code (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.   
  3. You may link to this code from another website, but ONLY if it is not wrapped in a frame. 
  4. You will abide by any additional copyright restrictions which the author may have placed in the code or code's description.
				
//**************************************
// Name: A simple universal comparator
// Description:You can use this class to sort an array of Objects without creating custom Comparators for each field. For example, if you have a class Employee, with methods getName() and getSalary(), you can simply do Arrays.sort(myEmployeeArray, new UniversalComparator("getName", 1)) or Arrays.sort(myEmployeeArray, new UniversalComparator("getSalary", -1)). The first statement would sort your array in ascending order by the value of getName() method, the second would sort it in descending order by the value of getSalary() method. The class uses the reflection API to accomplish this task.
// By: Lone Deranger
//
// Assumes:You need to import java.util.Arrays, java.util.Comparator in order to use Arrays.sort(). The return value of your Object's methods MUST implement the Comparable interface.
//
//This code is copyrighted and has// limited warranties.Please see http://www.Planet-Source-Code.com/vb/scripts/ShowCode.asp?txtCodeId=3308&lngWId=2//for details.//**************************************

import java.lang.Object;
import java.lang.reflect.*;
import java.util.Comparator;
public class UniversalComparator extends Object implements Comparator {
	private String methodName = "toString";
	private int descAscIndicator = 1;
	
	public static final int ASCENDING = 1;
	public static final int DESCENDING = -1;
	
	public UniversalComparator(int descAscIndicator) {
		this.descAscIndicator = descAscIndicator;
	}
	
	public UniversalComparator(String methodName, int descAscIndicator) {
		this(descAscIndicator);
		this.methodName = methodName;
	}
	
	public int compare(Object o1, Object o2) {
		Object comp1 = null;
		Object comp2 = null;
		try {
		Method o1_Method = o1.getClass().getMethod(methodName, null);
		Method o2_Method = o2.getClass().getMethod(methodName, null);
		comp1 = o1_Method.invoke(o1, null);
		comp2 = o2_Method.invoke(o2, null);
		
		} catch (NoSuchMethodException e) {
		} catch (IllegalAccessException e) {
		} catch (InvocationTargetException e) {}
		Comparable c1 = (Comparable) comp1;
		Comparable c2 = (Comparable) comp2;
		return c1.compareTo(c2) * descAscIndicator;
	}
	
	public boolean equals(Object obj) {
		return this.equals(obj);
	}
}


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this code (in the Advanced category)?
(The code with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)
 

Other User Comments
8/9/2006 1:51:22 PMSteve Davidson

I am trying to use this code to compare the properties of an instance of an array that I access using getProperty("asset_type") for example. There is no get method for each property.

Can you suggest how to modify this to be able to compare properties using a getProperty("the_property_name") method call?
(If this comment was disrespectful, please report it.)

 

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular code, please click here instead.)
 

To post feedback, first please login.