File: RJavaComparator.java

package info (click to toggle)
rjava 1.0-14-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,188 kB
  • sloc: java: 13,223; ansic: 5,503; sh: 3,776; xml: 325; makefile: 250; perl: 33
file content (52 lines) | stat: -rw-r--r-- 1,632 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import java.lang.Comparable ; 

/**
 * Utility class to compare two objects in the sense
 * of the java.lang.Comparable interface
 *
 */
public class RJavaComparator {
	           
	/**
	 * compares a and b in the sense of the java.lang.Comparable if possible
	 *
	 * <p>instances of the Number interface are treated specially, in order to 
	 * allow comparing Numbers of different classes, for example it is allowed 
	 * to compare a Double with an Integer. if the Numbers have the same class,
	 * they are compared normally, otherwise they are first converted to Doubles
	 * and then compared</p>
	 * 
	 * @param a an object
	 * @param b another object 
	 * 
	 * @return the result of <code>a.compareTo(b)</code> if this makes sense
	 * @throws NotComparableException if the two objects are not comparable
	 */
	public static int compare( Object a, Object b ) throws NotComparableException{
		int res ; 
		if( a.equals( b ) ) return 0 ;
		
		// treat Number s separately
		if( a instanceof Number && b instanceof Number && !( a.getClass() == b.getClass() ) ){
			Double _a = Double.valueOf( ((Number)a).doubleValue() );
			Double _b = Double.valueOf( ((Number)b).doubleValue() );
			return _a.compareTo( _b ); 
		}
		
		if( ! ( a instanceof Comparable ) ) throw new NotComparableException( a ); 
		if( ! ( b instanceof Comparable ) ) throw new NotComparableException( b ); 
		
		try{
			res = ( (Comparable)a ).compareTo( b ) ; 
		} catch( ClassCastException e){
			try{
				res = - ((Comparable)b).compareTo( a ) ;
			} catch( ClassCastException f){
				throw new NotComparableException( a, b ); 
			}
		}
		return res ;
	}
	
}