Collections类
Collections is not Collection.
Arrays类是用来操作数组的,它的方法全部都是静态的。
Collections类是用来操作集合的,它的方法全部都是静态的。
Arrays可以使用sort方法对数组进行排序。
Collections也可以使用sort方法对集合进行排序。
Arrays类使用sort对数组进行排序之前,该数组中的元素应该要实现Comparable接口。
同样,Collections.sort(Collection<T> c);之前,列表当中所有的元素都应该实现Comparable接口。
int num;
String name;
public Student( int num, String name) {
this .num = num;
this .name = name;
}
public String toString() {
return " 学号: " + num + " 姓名: " + name;
}
public int compareTo(Object o) {
Student s = (Student) o;
return num > s.num ? 1 : (num == s.num ? 0 : - 1 );
}
}
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
public class CollectionsTest {
public static void printElement(Collection c) {
Iterator i = c.iterator();
while (i.hasNext()) {
System.out.println(i.next());
}
}
public static void main(String[] args) {
Student s1 = new Student( 2 , " zhangsan " );
Student s2 = new Student( 1 , " lisi " );
Student s3 = new Student( 3 , " wangwu " );
ArrayList cn = new ArrayList();
// List cn = new ArrayList(); // List接口中也有sort方法
// Collection cn = new ArrayList(); // 该方法排序(List<T>中)在类型集合是不适用的参数(List)
cn.add(s1);
cn.add(s2);
cn.add(s3);
Collections.sort(cn);
printElement(cn);
}
}
int x, y;
public Point( int x, int y) {
super ();
this .x = x;
this .y = y;
}
@Override
public String toString() {
return " x= " + x + " ,y= " + y;
}
@Override
public int compareTo(Point o) {
int result = 0 ;
result = x > o.x ? 1 : (x == o.x ? 0 : - 1 );
if (result == 0 ) {
result = y > o.y ? 1 : (y == o.y ? 0 : - 1 );
}
return result;
}
}
反序排列: reverseOrder(),返回的就是一个Comparator对象。
Collections.sort(Collection c, Collections.reverseOrder());
在对列表进行排序的时候同时可以指定一个比较器,让这个列表遵照在比较器当中所设定的排序方式进行排序,这就提供了更大的灵活性,public static void sort(List l, Comparator c)。这个Comparator同样是一个在java.util包中的接口这个接口中有两个方法:int compare(T o1, T o2)和boolean equals(Object obj)。compare比较的是两个对象之间是按照什么样的方式进行排序,当对象o1大于对象o2 的时候返回正数,当对象o1等于对象o2的时候返回0,当对象o1小于对象o2返回负数;equals()方法没有实现但是jvm没有报错,因为所有的类都是派生自Object,在Object类中也有这个方法。所以能编译成功。这个比较器总是和一个指定的类相关,如果要对学生进行排序,因为要用到学生的num,所以要将Object类型转换成Student类型(没有使用泛型的情况下),这样才能调用它的它的成员变量num。
int num;
String name;
// 下面是学生自己提供的比较器
static class StudentCompare implements Comparator {
public int compare(Object o1, Object o2) {
Student s1 = (Student) o1; // 转型
Student s2 = (Student) o2; // 转型
int result = s1.num > s2.num ? 1 : (s1.num == s2.num ? 0 : - 1 );
if (result == 0 ) {
result = s1.name.compareTo(s2.name);
}
return result;
}
}
public Student( int num, String name) {
this .num = num;
this .name = name;
}
public String toString() {
return " 学号: " + num + " 姓名: " + name;
}
}