标签:
1 package com.sun; 2 3 public class ComparatorDemo implements Comparable<ComparatorDemo> { 4 5 private String name; 6 private Integer age; 7 private float score; 8 9 public ComparatorDemo(String name, Integer age, float score) { 10 super(); 11 this.name = name; 12 this.age = age; 13 this.score = score; 14 } 15 16 @Override 17 public String toString() { 18 return "name:" + name + ";age:" + age + ";score:" + score; 19 } 20 21 @Override 22 public int compareTo(ComparatorDemo o) { 23 if (this.score > o.score)// score是private的,为什么能够直接调用,这是因为在Student类内部 24 return -1;// 由高到底排序 25 else if (this.score < o.score) 26 return 1; 27 else { 28 if (this.age > o.age) 29 return 1;// 由底到高排序 30 else if (this.age < o.age) 31 return -1; 32 else 33 return 0; 34 } 35 } 36 37 public String getName() { 38 return name; 39 } 40 41 public void setName(String name) { 42 this.name = name; 43 } 44 45 public Integer getAge() { 46 return age; 47 } 48 49 public void setAge(Integer age) { 50 this.age = age; 51 } 52 53 public float getScore() { 54 return score; 55 } 56 57 public void setScore(float score) { 58 this.score = score; 59 } 60 61 }
1 package com.sun; 2 3 import java.util.ArrayList; 4 import java.util.Arrays; 5 import java.util.Collections; 6 import java.util.List; 7 8 public class ComparatorTest { 9 10 public static void main(String[] args) { 11 List<ComparatorDemo> lists = new ArrayList<>(); 12 lists.add(new ComparatorDemo("a", 4, 4)); 13 lists.add(new ComparatorDemo("b", 3, 6)); 14 lists.add(new ComparatorDemo("c", 2, 3)); 15 lists.add(new ComparatorDemo("d", 1, 7)); 16 Collections.sort(lists); 17 for (ComparatorDemo comparatorDemo : lists) { 18 System.out.println("++++++" + comparatorDemo); 19 } 20 21 ComparatorDemo com[] = {new ComparatorDemo("a", 4, 4), 22 new ComparatorDemo("b", 3, 6), 23 new ComparatorDemo("c", 2, 3), 24 new ComparatorDemo("d", 1, 7)}; 25 Arrays.sort(com); 26 for (ComparatorDemo comparatorDemo : com) { 27 System.out.println("------" + comparatorDemo); 28 } 29 } 30 }
标签:
原文地址:http://www.cnblogs.com/sun-space/p/5599153.html