您的位置:首页 > 其它

Collections的Comparable,Comparator

2016-06-13 00:17 429 查看
package com.imooc.collection;

import java.util.HashSet;
import java.util.Set;
/**
* 学生类
* @author Monica
*
*/

public class Student implements Comparable<Student>{
public String id;
public String name;
public Set<Course> courses;
public Student(String id,String name){
this.id = id;
this.name = name;
this.courses = new HashSet<Course>();//set接口调用
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof Student))
return false;
Student other = (Student) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@Override
public int compareTo(Student o) {
// TODO 自动生成的方法存根
return this.id.compareTo(o.id);
}

}


package com.imooc.collection;

import java.util.Comparator;

public class StudentComparator implements Comparator<Student> {

@Override
public int compare(Student o1, Student o2) {
// TODO Auto-generated method stub
return o1.name.compareTo(o2.name);
}

}


package com.imooc.collection;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

public class CollectionsTest {
/**
* 3.对其他类型泛型的List进行排序,以Student为例
* @param args
*/
public void testSort4(){
List<Student> studentList = new ArrayList<Student>();
Random random = new Random();

studentList.add(new Student(random.nextInt(1000)+"","Jim"));
studentList.add(new Student(random.nextInt(1000)+"","Lily"));
studentList.add(new Student(random.nextInt(1000)+"","Monica"));
studentList.add(new Student(10000+"","Beyond"));
System.out.println("----------排序前----------");
for (Student student : studentList) {
System.out.println("学生:"+student.id+":"+student.name);
}
Collections.sort(studentList);
System.out.println("------------排序后------------");
for (Student student : studentList) {
System.out.println("学生:"+student.id+":"+student.name);
}
Collections.sort(studentList,new StudentComparator());
System.out.println("----------按照姓名排序后-----------");
for (Student student : studentList) {
System.out.println("学生:"+student.id+":"+student.name);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
CollectionsTest ct = new CollectionsTest();
ct.testSort4();
}

}


演示结果:

----------排序前----------
学生:89:Jim
学生:955:Lily
学生:29:Monica
学生:10000:Beyond
------------排序后------------
学生:10000:Beyond
学生:29:Monica
学生:89:Jim
学生:955:Lily
----------按照姓名排序后-----------
学生:10000:Beyond
学生:89:Jim
学生:955:Lily
学生:29:Monica
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息