程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> Java中文排序

Java中文排序

編輯:關於JAVA
第一種情況:

  1. Comparator cmp = Collator.getInstance(java.util.Locale.CHINA);
  2.  
  3. String[] arr = { "張三", "李四", "王五", "劉六" };
  4. Arrays.sort(arr, cmp);
  5. for (int i = 0; i < arr.length; i++)
  6. 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);
// return collator.compare(((CollationKey) c1).getSourceString(),
// ((CollationKey) c2).getSourceString());
return collator.compare(((CollationKey) c2).getSourceString(),
((CollationKey) c1).getSourceString());
}
// public int compare(ComparableBean obj1, ComparableBean obj2) {
// String tempname1 = obj1.getName();
// String tempname2 = obj2.getName();
//
// CollationKey c1 = collator.getCollationKey(tempname1);
// CollationKey c2 = collator.getCollationKey(tempname2);
// return collator.compare(((CollationKey) c1).getSourceString(),
// ((CollationKey) c2).getSourceString());
// }
}
//the end of ComparableBean.java

測試代碼:

ComparableBean[] nameContent = { new ComparableBean("一切從實際出發"),
new ComparableBean("立於不敗之地"), new ComparableBean("多項式"),
new ComparableBean("貫徹落實"), new ComparableBean("密切聯系群眾"),
new ComparableBean("四項基本原則"), new ComparableBean("咬牙切齒"),
new ComparableBean("恭恭敬敬"), new ComparableBean("民警"),
new ComparableBean("經營承包責任制") };
Arrays.sort(nameContent,new ComparableBeanComparator());
for (int i = 0; i < nameContent.length; i++) {
System.out.println(nameContent[i].getName());
}
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved