ITeye博客

list排序

hao861002 · 2009-02-06 11:28 · java软件 · Markdown

  1. import java.text.Collator;
  2. import java.util.ArrayList;
  3. import java.util.Collections;
  4. import java.util.Comparator;
  5. import java.util.Iterator;
  6. public class ChineseCharacterSortDemo {
  7. public static void main(String args[]) {
  8. ArrayList list = new ArrayList();
  9. list.add(new Country(86, "中国"));
  10. list.add(new Country(21, "加拿大"));
  11. list.add(new Country(1, "美国"));
  12. list.add(new Country(110, "阿富汗"));
  13. Comparator cmp = new ChinsesCharComp();
  14. Collections.sort(list, cmp);
  15. Iterator iter = list.iterator();
  16. while (iter.hasNext()) {
  17. Country s1 = (Country) iter.next();
  18. System.out.println(s1.getCode() + "----" + s1.getName());
  19. }
  20. }
  21. }
  22. class ChinsesCharComp implements Comparator {
  23. public int compare(Object o1, Object o2) {
  24. Country c1 = (Country) o1;
  25. Country c2 = (Country) o2;
  26. Collator myCollator = Collator.getInstance(java.util.Locale.CHINA);
  27. if (myCollator.compare(c1.getName(), c2.getName()) < 0)
  28. return -1;
  29. else if (myCollator.compare(c1.getName(), c2.getName()) > 0)
  30. return 1;
  31. else
  32. return 0;
  33. }
  34. }
  35. class Country {
  36. private long code;
  37. private String name;
  38. public long getCode() {
  39. return code;
  40. }
  41. public void setCode(long code) {
  42. this.code = code;
  43. }
  44. public String getName() {
  45. return name;
  46. }
  47. public void setName(String name) {
  48. this.name = name;
  49. }
  50. public Country() {
  51. }
  52. public Country(long code, String name) {
  53. this.code = code;
  54. this.name = name;
  55. }
  56. }

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。