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. }
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
我们该使用ArrayList还是LinkedList?
我们该使用ArrayList还是LinkedList?
ArrayList LinkedList