Java 数组排序

1.对于我们自定义的实体类只需要实现 Comparable 接口

class Employee implements Comparable<Employee>{





   String name;

   int age;





   public String getName() {

      return name;

   }





   public void setName(String name) {

      this.name = name;

   }





   public int getAge() {

      return age;

   }





   public void setAge(int age) {

      this.age = age;

   }





   public Employee() {};





   public Employee(String name, int age) {

      super();

      this.name = name;

      this.age = age;

   }





   public static String staticString() {

      return "static method.";

   }





   @Override

   public String toString() {

      return String.format("%s[name=%s, age=%d]", getClass().getName(), this.name, this.age);

   }





   @Override

   public int compareTo(Employee o) {

      return Integer.compare(this.age, o.age);

   }

}


Employee[] employees = {new Employee("a", 2), new Employee("b", 1), new Employee("c", 3)};

Arrays.sort(employees);

System.out.println(Arrays.toString(employees));



2.对于第三方库中实体类我们需要排序,则要实现 Comparator 接口。如 String 默认时根据字典排序,先使用长度排序;

class LengthComparator implements Comparator<String> {





    @Override

    public int compare(String s1, String s2) {

        return s1.length() - s2.length();

    }

}


String[] words = {"aa", "bbb", "cc"};

Arrays.sort(words, new LengthComparator());

System.out.println(Arrays.toString(words));


 

 

展开阅读全文