001 package edu.nrao.sss.sort; 002 003 import java.util.Comparator; 004 005 /** 006 * A sort key for {@code String}s. 007 * <p/> 008 * The most common way to extend this class is to subclass it into a class 009 * that also implements {@link Comparator}. The main job of the subclass 010 * is to provide the strings to this parent class. Example: 011 * <pre> 012 * /** 013 * * Sorts persons based on their names (surname then given names). 014 * */ 015 * public class PersonNameKey extends StringSortKey 016 * implements Comparator<Person> 017 * { 018 * public int compare(Person p1, Person p2) 019 * { 020 * return compareObjects(p1.getNameLastFirst(), p2.getNameLastFirst()); 021 * } 022 * }</pre> 023 * <p> 024 * Clients of the example <tt>PersonNameKey</tt> class are able to configure 025 * that comparator via the {@link #setOrder(SortOrder) setOrder} and 026 * {@link #setIgnoreCase(boolean) setIgnoreCase} methods, something they cannot 027 * do with the plain <tt>Comparator</tt> interface. They may then place 028 * instances of this class in a {@link CompoundComparator}.</p> 029 * <p> 030 * <b>Version Info:</b> 031 * <table style="margin-left:2em"> 032 * <tr><td>$Revision: 593 $</td></tr> 033 * <tr><td>$Date: 2007-05-07 15:54:14 -0600 (Mon, 07 May 2007) $</td></tr> 034 * <tr><td>$Author: dharland $</td></tr> 035 * </table></p> 036 * 037 * @author David M. Harland 038 * @since 2007-05-03 039 */ 040 public abstract class StringSortKey 041 extends SortKey<String> 042 { 043 private boolean ignoreCase; 044 045 /** Helps create a new, case-sensitive, instance. */ 046 protected StringSortKey() 047 { 048 super(); 049 050 ignoreCase = false; 051 } 052 053 /** 054 * Tells this key to either consider or ignore case when comparing strings. 055 * @param ignore a value of <i>true</i> will instruct this key to ignore 056 * case when comparing strings. 057 */ 058 public void setIgnoreCase(boolean ignore) 059 { 060 ignoreCase = ignore; 061 } 062 063 /** 064 * Uses the natural ordering of {@code String} and the value 065 * of this key's {@code ignoreCase} property. 066 */ 067 protected int compareNatural(String o1, String o2) 068 { 069 return ignoreCase ? o1.compareToIgnoreCase(o2) : o1.compareTo(o2); 070 } 071 072 /** 073 * Uses the natural ordering of {@code String} and the value 074 * of this key's {@code ignoreCase} property. 075 */ 076 protected int compareAscending(String o1, String o2) 077 { 078 return compareNatural(o1, o2); 079 } 080 }