Java编程中怎样实现中文排序
2008-01-05 20:31:51 来源:WEB开发网核心提示:第一种情况:Comparator cmp = Collator.getInstance(java.util.Locale.CHINA); String[] arr = { "张三", "李四", "王五", "刘六" }; Arrays.
第一种情况:
第二种情况:
//ComparableBean.java
import java.text.CollationKey;
import java.text.Collator;
import java.text.RuleBasedCollator;
import java.util.Comparator;
public class ComparableBean{
private String name;
public ComparableBean(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class ComparableBeanComparator implements Comparator//<ComparableBean>
{
RuleBasedCollator collator; // you can set your rules for the instance "collator"
public ComparableBeanComparator()
{
collator = (RuleBasedCollator)Collator.getInstance(java.util.Locale.CHINA);// try testing various locales
}
public int compare(Object obj1, Object obj2) {
String tempname1 = ((ComparableBean) obj1).getName();
String tempname2 = ((ComparableBean) obj2).getName();
CollationKey c1 = collator.getCollationKey(tempname1);
CollationKey c2 = collator.getCollationKey(tempname2);
- Comparator cmp = Collator.getInstance(java.util.Locale.CHINA);
- String[] arr = { "张三", "李四", "王五", "刘六" };
- Arrays.sort(arr, cmp);
- for (int i = 0; i < arr.length; i++)
- System.out.PRintln(arr[i]);
第二种情况:
//ComparableBean.java
import java.text.CollationKey;
import java.text.Collator;
import java.text.RuleBasedCollator;
import java.util.Comparator;
public class ComparableBean{
private String name;
public ComparableBean(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class ComparableBeanComparator implements Comparator//<ComparableBean>
{
RuleBasedCollator collator; // you can set your rules for the instance "collator"
public ComparableBeanComparator()
{
collator = (RuleBasedCollator)Collator.getInstance(java.util.Locale.CHINA);// try testing various locales
}
public int compare(Object obj1, Object obj2) {
String tempname1 = ((ComparableBean) obj1).getName();
String tempname2 = ((ComparableBean) obj2).getName();
CollationKey c1 = collator.getCollationKey(tempname1);
CollationKey c2 = collator.getCollationKey(tempname2);
更多精彩
赞助商链接