ArrayList 对象排序实例

  1. import java.util.ArrayList;   
  2. import java.util.Collection;   
  3. import java.util.Collections;   
  4. import java.util.Comparator;   
  5.   
  6.   
  7. public class SortTwo implements Comparator {   
  8. //排序字段   
  9. private String sort1;   
  10. //排序方式   
  11. private int state;   
  12. public SortTwo(int state){   
  13. this.state=state;   
  14. }   
  15. public SortTwo(){   
  16.   
  17. }   
  18. public int SortUp(Object o1,Object o2){   
  19. Student stu=(Student) o1;   
  20. Student stu1=(Student) o2;   
  21. if(sort1.equals("name")){   
  22. if(stu.getName().compareTo(stu1.getName())>1){   
  23. return 1;   
  24. else if(stu.getName().compareTo(stu1.getName())<1){   
  25. return -1;   
  26. }else{   
  27. return 0;   
  28. }   
  29. }   
  30. if(sort1.equals("age")){   
  31. if(stu.getAge().compareTo(stu1.getAge())>1){   
  32. return 1;   
  33. else if(stu.getAge().compareTo(stu1.getAge())<1){   
  34. return -1;   
  35. }else{   
  36. return 0;   
  37. }   
  38. }   
  39. return 0;   
  40. }   
  41. public int SortDOWN(Object o1,Object o2){   
  42. Student stu=(Student) o1;   
  43. Student stu1=(Student) o2;   
  44. if(sort1.equals("name")){   
  45. if(stu.getName().compareTo(stu1.getName())>1){   
  46. return -1;   
  47. else if(stu.getName().compareTo(stu1.getName())<1){   
  48. return 1;   
  49. }else{   
  50. return 0;   
  51. }   
  52. }   
  53. if(sort1.equals("age")){   
  54. if(stu.getAge().compareTo(stu1.getAge())>1){   
  55. return -1;   
  56. else if(stu.getAge().compareTo(stu1.getAge())<1){   
  57. return 1;   
  58. }else{   
  59. return 0;   
  60. }   
  61. }   
  62. return 0;   
  63. }   
  64. public int compare(Object o1, Object o2) {   
  65.   
  66. if(this.state==1){   
  67. return SortUp(o1, o2);   
  68. }else{   
  69. return SortDOWN(o1, o2);   
  70. }   
  71. }   
  72.   
  73. /**  
  74. * @param args  
  75. */  
  76. public static void main(String[] args) {   
  77. // TODO Auto-generated method stub   
  78. Student stu=new Student();   
  79. stu.setName("123");   
  80. stu.setAge("12");   
  81. Student stu1=new Student();   
  82. stu1.setName("234");   
  83. stu1.setAge("23");   
  84. ArrayList<Student>list=new ArrayList<Student>();   
  85. list.add(stu);   
  86. list.add(stu1);   
  87. SortTwo t=new SortTwo(1);   
  88. t.sort1="age";   
  89. Collections.sort(list,t);   
  90. for(Student st : list){   
  91. System.out.println(st.getName() +"   "+st.getAge());   
  92. }   
  93. }   
  94.   
  95. }   

 

 

文章来自: http://bill-sbia.iteye.com/blog/189729

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值