方式:
- 可以使用String类的
compareTo()
方法来实现。该方法用于判断一个字符串是大于、等于还是小于另一个字符串,返回int
类型的差值。判断字符串大小的依据是它们在字典中的顺序。 示例如下:public class Demo1 { public static void main(String[] args) { //字符串的比较 String s = "123"; String s1 = "中国"; int i = s.compareTo(s1); System.out.println(i); } }
- 实现Comparable接口
/* * Student类 * name,grade、score三个属性 */ public class Student implements Comparable<Student> { private String name; private int grade; private int score; @Override public int compareTo(Student o) { if (null == o) { return -1; } // grade小的排前面 if (this.grade < o.getGrade()) { return -1; // grade大的排后面 } else if (this.grade > o.getGrade()) { return 1; // 若grade相同,则比较score } else { // score小的排后面 if (this.score < o.getScore()) { return 1; // score大的排前面 } else if (this.score > o.getScore()) { return -1; } else { return 0; } } } @Override public String toString() { return this.name + "," + this.grade + "," + this.score; } /* * getter and setter */ }
public class TestSort { public static void main(String[] args) { List<Student> stulist = new ArrayList<Student>(); // 初始化学生对象,添加到list中 stulist.add(new Student("Curry", 4, 95)); stulist.add(new Student("Harden", 5, 92)); stulist.add(new Student("James", 5, 94)); stulist.add(new Student("Kobe", 6, 91)); stulist.add(new Student("Durant", 4, 94)); stulist.add(new Student("Rose", 5, 97)); // 利用Collections工具进行排序 Collections.sort(stulist); // 输出验证 for (Student s : stulist) { System.out.println(s); } } }
- 实现Comparator接口
public class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public Person() { } 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; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
import java.util.Comparator; public class PersonComparator implements Comparator<Person> { @Override public int compare(Person o1, Person o2) { // if (o1.getAge() > o2.getAge()) // return 1; // else if (o1.getAge() == o2.getAge()) // return 0; // return -1; // 以上代码其实可以用Integer类的compare方法代替 return Integer.compare(o1.getAge(), o2.getAge()); } }
import java.util.Arrays; public class PersonCompareTest { public static void main(String[] args) { Person[] people = { new Person("张三", 17), new Person("李四", 20), new Person("麻子", 18), }; Arrays.sort(people, new PersonComparator()); for (Person p: people) { System.out.println(p.toString()); } } }