1. 程式人生 > >對集合中的元素進行排序,接口Comparator<T>和Comparable<T>的使用

對集合中的元素進行排序,接口Comparator<T>和Comparable<T>的使用

pub length 自定義 長度 public bsp imp ide 抽象類

關於比較排序比較的接口 或者是類有:java.lang.Comparable<T>接口,

一個抽象類通過實現這個接口可以進行自然排序,也就是一個如果一個自定義類通過implements關鍵字實現Comparable<T>接口,並且要重寫這個接口中的CompareTo()抽象方法,可以再這個方法中定義自己的比較規則;然後再向集合對象中添加元素的時候,就會自動調用compareTo()方法,對集合中的元素進行排序。

對於實現這個接口的類的對象,可以使用Collections類中的靜態方法,sort()進行自動排序。

public class Student implements Comparable<Student> {

private String name;

private int age;

public int compareTo(Student o) {

int num = this.age-o.age;

return num==0 ? this.name.compareTo(o.name): num;

}

在main()方法中可以使用:

TreeSet<Student> ts = new TreeSet<>();

ts.add(new Student("張三",23));

ts.add(new Student("趙琪",23));

ts.add(new Student("李四",32));

ts.add(new Student("王五",78));

ts.add(new Student("趙六",26));

System.out.println(ts);

實現對添加到TreeSet集合中的元素進行排序。

還有一中實現集合中的元素進行排序的方法:另外自定義一個比較器類實現Comparator<T>接口,然後在這個比較器類中重寫compare()方法,在這個方法中定義自己的比較規則;在需要使用的時候可以將一個比較器的對象(也就是Comparator<T>接口的子類對象,可以使用匿名內部類實現)傳給集合的構造方法,再向集合中添加元素的時候就可以實現對集合中的元素進行排序。

實例:

定義一個比較器:

class CompareByLen implements Comparator<String>{//比較器

@Override

public int compare(String o1, String o2) {

//比較字符串的長度

int num = o1.length() - o2.length();

//如果字符串的長度相同,就按照字母的順序比較

return num == 0 ? o1.compareTo(o2) : num;

}

在main()方法中可以通過:

TreeSet<String> ts = new TreeSet<>(new CompareByLen());

ts.add("ffffff");

ts.add("a");

ts.add("ef");

ts.add("gan");

ts.add("rs");

System.out.println(ts);

實現對要添加到集合中的元素進行排序。

這種方法就是—比較器方法。

Java.util.Comparator<T>

對集合中的元素進行排序,接口Comparator<T>和Comparable<T>的使用