java.lang.Comparable应用1:比较和排序[分享]
本人在工作中用到一个平时很少用的接口 java.,突然觉得它很好用,所以拿来给大家分享下,我个人觉得看例子说话比较实际点,希望看的人能从例子中获得收获!这个例子比较简单我也不多加注释。
1. import java.util.Iterator;
2. import java.util.Map;
3. import java.util.TreeMap;
4. /**
5. * 这个是jdk1.4的版本,如果在1.5中会用得更加简单,这里我就不在多写
6. * 用于基于LogoOrde的排序,先根据logoOrder_displayOrder排序asc,再根据logoOrder_Id排序desc
7. * @author huanglq
8. *
9. */
10. public class LogoOrder implements Comparable{
11.
12. int logoOrder_Id;
13.
14. int logoOrder_displayOrder;
15.
16. public LogoOrder(int logoOder_displayOrder,int logoOrder_Id) {
17. super();
18. this.logoOrder_displayOrder = logoOder_displayOrder;
19. this.logoOrder_Id = logoOrder_Id;
20.
21. }
22.
23. public int getLogoOrder_displayOder() {
24. return logoOrder_displayOrder;
25. }
26.
27. public void setLogoOrder_displayOder(int logoOder_displayOrder) {
28. this.logoOrder_displayOrder = logoOder_displayOrder;
29. }
30.
31. public int getLogoOrder_Id() {
32. return logoOrder_Id;
33. }
34.
35. public void setLogoOrder_Id(int logoOrder_Id) {
36. this.logoOrder_Id = logoOrder_Id;
37. }
38.
39. public int compareTo(Object o) {
40. int order=this.logoOrder_displayOrder-((LogoOrder)o).logoOrder_displayOrder; ////先根据logoOrder_displayOrder排序asc
41. if(order!=0){
42. return order;
43. }else{
44. return ((LogoOrder)o).logoOrder_Id-this.logoOrder_Id; //再根据logoOrder_Id排序desc
45. }
46. }
47.
48. public String toString(){
49. return "logoOrder_displayOder:"+logoOrder_displayOrder+" logoOder_Id:"+logoOrder_Id;
50. }
51. //测试,当然大家可以写的和我不一样,既然是用于排序就很有可能用到TreeSet和TreeMap,看具体情况
52. public static void main(String[] args){
53. Map map2=new TreeMap();
54. LogoOrder lo1=new LogoOrder(1,2);
55. map2.put(lo1, "two");
56. map2.put(new LogoOrder(1,1), "one");
57. map2.put(new LogoOrder(2,1), "three");
58. map2.put(new LogoOrder(2,1), "THREE@");
59. Iterator it2=map2.keySet().iterator();
60. while(it2.hasNext()){
61. System.out.println(it2.next());
62. }
63. System.out.println(map2.get(new LogoOrder(2,1)));
64. }
65.
66. }
67. /**
68. 输出结果:
69. logoOrder_displayOder:1 logoOder_Id:2
70. logoOrder_displayOder:1 logoOder_Id:1
71. logoOrder_displayOder:2 logoOder_Id:1
72. THREE@ ---说明Map如果加入了一样的key,则这个key值的value会覆盖掉原来的value
73. */