01: /*
02: * FunctionComparator.java
03: *
04: * Copyright (c) 1997-2006 Sun Microsystems, Inc. All Rights Reserved.
05: *
06: * See the file "LICENSE.txt" for information on usage and redistribution
07: * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
08: */
09: package org.pnuts.lib;
10:
11: import pnuts.lang.PnutsFunction;
12: import pnuts.lang.Context;
13: import pnuts.lang.Runtime;
14: import java.util.Comparator;
15:
16: /**
17: * Comparator that compares the results of function calls.
18: */
19: public class FunctionComparator implements Comparator {
20: private PnutsFunction func;
21: private Context context;
22: private int equalValue;
23:
24: /**
25: * Constructor
26: *
27: * @param func the results of the function are compared
28: * @param context the context in which the function is called
29: */
30: public FunctionComparator(PnutsFunction func, Context context) {
31: this (func, context, 0);
32: }
33:
34: /**
35: * Constructor
36: *
37: * @param func the results of the function are compared
38: * @param context the context in which the function is called
39: * @param equalValue compare() returns this when two objects are equal; the default is 0
40: */
41: public FunctionComparator(PnutsFunction func, Context context,
42: int equalValue) {
43: this .func = func;
44: this .context = context;
45: this .equalValue = equalValue;
46: }
47:
48: public int compare(Object obj1, Object obj2) {
49: Object o1 = func.call(new Object[] { obj1 }, context);
50: Object o2 = func.call(new Object[] { obj2 }, context);
51: if (equalValue == 0) {
52: return Runtime.compareTo(o1, o2);
53: } else {
54: int result = Runtime.compareTo(o1, o2);
55: if (result == 0) {
56: if (obj1.equals(obj2)) {
57: return 0;
58: } else {
59: return equalValue;
60: }
61: } else {
62: return result;
63: }
64: }
65: }
66: }
|