JAVA认证

Java编程中如何实现中文排序

时间:2024-07-19 00:15:01 JAVA认证 我要投稿
  • 相关推荐

Java编程中如何实现中文排序

  在不断的Java学习中,我们就能发现在很多的时候还是有不少的技巧。下面YJBYS小编为大家整理了关于Java编程中如何实现中文排序的文章,希望对你有所帮助。

  第一种情况:

  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//

  {

  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());

  }

【Java编程中如何实现中文排序】相关文章:

Java如何实现点的在线添加08-31

word表格中的数据如何排序07-10

关于JAVA的XML编程09-03

Java基本编程技巧09-03

PHP中多态如何实现呢10-29

在word中如何实现自动续表06-23

java程序中如何调用linux命令06-13

Java中如何构造、生成XML简明09-02

关于JAVA实现httpClient的实例11-05

Java多线程的实现方式11-03