用TreeMap实现java中英文排序代码
时间:2011-03-26
在中文排序中发现不能正排序,这是字符国际化问题引起的,可以实现Comparator接口,使用Collator类来解决!
...
import java.text.Collator;
public class CollatorComparator implements Comparator
{
Collator collator = Collator.getInstance();
public int compare(Object element1, Object element2)
{
CollationKey key1 = collator.getCollationKey(element1.toString());
CollationKey key2 = collator.getCollationKey(element2.toString());
return key1.compareTo(key2);
}
}
运行:
TreeMap map = new TreeMap(new CollatorComparator());
map.put("1", "1");
map.put("华", "华");
map.put("花", "花");
Collection col = map.values(); I
terator it = col.iterator();
while(it.hasNext()
)
{
System.out.println(it.next());
}
|