View Javadoc

1   /*
2   Wotonomy: OpenStep design patterns for pure Java applications.
3   Copyright (C) 2000 Intersect Software Corporation
4   
5   This library is free software; you can redistribute it and/or
6   modify it under the terms of the GNU Lesser General Public
7   License as published by the Free Software Foundation; either
8   version 2.1 of the License, or (at your option) any later version.
9   
10  This library is distributed in the hope that it will be useful,
11  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  Lesser General Public License for more details.
14  
15  You should have received a copy of the GNU Lesser General Public
16  License along with this library; if not, see http://www.gnu.org
17  */
18  
19  package net.wotonomy.foundation.internal;
20  
21  import java.io.Serializable;
22  import java.util.Comparator;
23  
24  
25  /***
26  * A Comparator that will sort elements based on the
27  * property specified in the constructor.
28  *
29  * @author michael@mpowers.net
30  * @author $Author: cgruber $
31  * @version $Revision: 893 $
32  */
33  public class PropertyComparator implements Comparator, Serializable
34  {
35      private String property;
36  
37  /***
38  * Standard constructor to configure the comparator.
39  * @param aProperty A property whose value is used to sort elements.
40  */
41      public PropertyComparator( String aProperty )
42      {
43  		property = aProperty;
44      }
45  
46      // interface Comparator
47  
48      public int compare(Object o1, Object o2)
49      {
50  		Object v1 = Introspector.get( o1, property );
51  		Object v2 = Introspector.get( o2, property );
52  		if ( v1 instanceof Comparable )
53  		{
54  			return ((Comparable)v1).compareTo( v2 );
55  		}
56  		else
57  		if ( v2 instanceof Comparable )
58  		{
59  			return ((Comparable)v2).compareTo( v1 );
60  		}
61  		else
62  		{
63  			if ( v1 == null )
64  			{
65  				if ( v2 == null )
66  				{
67  					return 0; // both nulls are equal
68  				}
69  				return -1; // null is less than any object
70  			}
71  			else
72  			if ( v2 == null )
73  			{
74  				return 1; // any object is greater than null
75  			}
76  		}
77  		// last resort: compare string conversions
78  		return v1.toString().compareTo( v2.toString() );
79  	}
80  	
81  	public boolean equals( Object obj )
82  	{
83  		return ( obj instanceof PropertyComparator );	
84  	}
85  }
86  
87  /*
88   * $Log$
89   * Revision 1.2  2006/02/16 13:11:47  cgruber
90   * Check in all sources in eclipse-friendly maven-enabled packages.
91   *
92   * Revision 1.1.1.1  2000/12/21 15:52:07  mpowers
93   * Contributing wotonomy.
94   *
95   * Revision 1.2  2000/12/20 16:25:46  michael
96   * Added log to all files.
97   *
98   *
99   */
100