链表的节点按照添加顺序存储且相同数据不覆盖,而树集的节点默认升序存储且覆盖相同数据(自定义对象可以实现Comparable接口并重写compareTo方法,并保留相同数据)。Collections类对List对象提供了用于排序、查找等操作的类方法如下:
public static sort(List<E> list):将list中的元素按升序排列;
int binarySearch(List<T> list,T key, CompareTo<T>c):折半查找,compareTo函数返回0时查找成功
Collections类的其他方法:
public static void shuffle(List<E> list)将list中的数据按洗牌算法重新随机排列
static void rotate(List<E>list, int d)旋转链表中的数据。d取正数时,向右移动。
public static void reverse(List<E>list) 翻转list中的数据。
java提供的Collections类中的sort方法是面向Comparable接口设计的,因此创建对象的类必须实现Comparable接口,并重写接口中的int compareTo(Object b)来规定对象的大小关系。
如下利用Collection.sort对象保存学生成绩数据的链表进行排序和查找:
import java.util.*;
class Student implements Comparable<Student>{//实现Comparable泛型接口
String name;
int score=0;
Student(String name,int score){
this.name=name;
this.score=score;
}
public int compareTo(Student stu){//由于是泛型接口指定了String类型,因此不必类型转换。
return score-stu.score;
}
}
public class Main {
public static void main(String[] args) {
LinkedList<Student> myList=new LinkedList<Student>();
myList.add(new Student("钱二",90));
myList.add(new Student("赵一",66));
myList.add(new Student("李三",86));
myList.add(new Student("孙四",66));
Iterator<Student> iter=myList.iterator();
System.out.println("排序前:");
while(iter.hasNext()){
Student t=iter.next();
System.out.println(t.name+" "+t.score);
}
Collections.sort(myList);//利用Collections排序
System.out.println("排序后:");
iter=myList.iterator();
while(iter.hasNext()){
Student t=iter.next();
System.out.println(t.name+" "+t.score);
}
Student zhang=new Student("张大",86);
System.out.println("\n查找");//查找,compareTo函数返回0时查找成功
int n=Collections.binarySearch(myList, zhang);
System.out.println(zhang.name+"分数与"+myList.get(n).name+myList.get(n).score+"分数相同");
System.out.println("\n洗牌后");//洗牌算法重新随机排列
Collections.shuffle(myList);
iter=myList.iterator();
while(iter.hasNext()){
Student t=iter.next();
System.out.println(t.name+" "+t.score);
}
System.out.println("\n翻转后");//翻转数据
Collections.reverse(myList);;
iter=myList.iterator();
while(iter.hasNext()){
Student t=iter.next();
System.out.println(t.name+" "+t.score);
}
}
}
输出:
排序前:
钱二 90
赵一 66
李三 86
孙四 66
排序后:
赵一 66
孙四 66
李三 86
钱二 90
查找
张大分数与李三86分数相同
洗牌后
孙四 66
赵一 66
钱二 90
李三 86
翻转后
李三 86
钱二 90
赵一 66
孙四 66