在中文排序中發現不能正排序,這是字符國際化問題引起的,可以實現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());
}