java阿里巴巴代码
源代码在线查看: stringcomparator.java
/**
* StringComparator.java
*
* This class is used along with TreeMap
* When put a key into a TreeMap, TreeMap will replace the old having the same key with the new
* but when you use this class, you can control this case
* though the key is the same, the Comparator will return false if you set the flag 'takeEqual=true'
*/
package tools.util;
import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeMap;
public class StringComparator implements Comparator
{
private int takeEqual = 0;
private boolean desc = false;
/**
* IntegerComparator, Constructor
* @param boolean takeEqual, if true, return 1 when equal,
*/
public StringComparator(boolean takeEqual)
{
this.takeEqual = (takeEqual==true) ? 1 : 0;
}
/**
* StringComparator, Constructor
* @param boolean takeEqual, if true, return 1 when equal,
* @param boolean desc
*/
public StringComparator(boolean takeEqual, boolean desc)
{
this.takeEqual = (takeEqual==true) ? 1 : 0;
this.desc = desc;
}
/**
* compare, compare 2 objects
* @param Object o1
* @param Object o2
* @return int, 1 ==> o1 > o2, -1 ==> o1 < o2, 0 ==> o1 = o2
*/
public int compare(Object o1, Object o2)
{
String str1 = ((String)o1).toUpperCase();
String str2 = ((String)o2).toUpperCase();
if (!desc) // ASC
{
if(str1.compareTo(str2) < 0) return -1;
if(str1.compareTo(str2) > 0) return 1;
}
else // DESC
{
if(str1.compareTo(str2) < 0) return 1;
if(str1.compareTo(str2) > 0) return -1;
}
return takeEqual;
}
public boolean equals(Object obj)
{
return false;
}
static public void main(String[] args)
{
test(true);
test(false);
}
static private void test(boolean flag)
{
System.out.println("\nflag: " + flag);
TreeMap map = new TreeMap(new StringComparator(flag));
String str1 = "string #1";
String str2 = "string #2";
String str3 = "string #2";
String str4 = "string #4";
map.put(str1, str1);
map.put(str2, str2);
map.put(str3, str3);
map.put(str4, str4);
for(Iterator it=map.values().iterator(); it.hasNext();)
{
String str = (String)it.next();
System.out.println("str: " + str);
}
}
}