Comparable & Comparator简介

在集合框架中,如果某个集合中的序列要使用Collections.sort()方法,则必需实现Comparable接口。

Comparable & Comparator

Comparable & Comparator简介_第1张图片

Comparable & Comparator简介_第2张图片

JAVA 集合框架的主要成员:

Comparable & Comparator简介_第3张图片

示例:创建一个Student类型(基本数据类型的包装类的List(集合)可直接使用Collections.sort()方法)的List,向其添加学生并通过Collections.sort()方           法排序输出。

1.创建学生类,继承Comparable接口

package imooc;

import java.util.HashSet;
import java.util.Set;

//学生类
public class Student implements Comparable{
	public String id;
	public String name;
	public Set courses;
	public Student(String id,String name){
		this.id=id;
		this.name=name;
		this.courses =new HashSet();
	}
@Override
	public int compareTo(Student o) {        //通过ID比较排序
		// TODO Auto-generated method stub
		return this.id.compareTo(o.id);
	}
	

}
2.创建一个studentComparator类,继承Comparator接口

package imooc;

import java.util.Comparator;

public class studentComparator implements Comparator {

	@Override
	public int compare(Student a, Student b) {   //通过姓名比较排序
		// TODO Auto-generated method stub
		return a.name.compareTo(b.name);
	}

}
测试类


package imooc;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
 //测试student类型的List
	   public void testStudent(){
		   List list3=new ArrayList();
		   Random random=new Random();
		   list3.add(new Student(random.nextInt(1000)+"","jack"));
		   list3.add(new Student(random.nextInt(1000)+"","anei"));
		   list3.add(new Student(random.nextInt(1000)+"","back"));
		   System.out.println("---排序前----");
		   for(Student s:list3){
			   System.out.println(s.id+" "+s.name);
		   }
		   System.out.println("---排序后----");
		   System.out.println("按照ID排序:");
		   Collections.sort(list3);
		   for(Student s:list3){
			   System.out.println(s.id+" "+s.name);
		   }
		   System.out.println("按照姓名排序:");
		   Collections.sort(list3,new studentComparator());
		   for( Student s2:list3){
			   System.out.println(s2.id+" "+s2.name );
		   }
		   
	   }
public static void main(String[] args) {
		testCollection it=new testCollection();
		it.testStudent();
结果:

Comparable & Comparator简介_第4张图片


你可能感兴趣的:(java)