一、comparable
要想使用sort()方法进行排序,就必须要有一个前提:对象所在的类一定要实现Comparable接口,否则代码执行时会出现ClassCastException异常
TreeSet是使用compare()方法实现排序
1.两个对象Compareto()比较结果如果是0,认为两个对象意义上是同一个对象,到二个会被去掉
2.两个对象equals()比较结果如果为true,说明他俩意义上是同一个对象,这样第二个应该去掉,为了保证第二个对象被去掉,所以他们的Compareto()比较结果一定为o
3.重写equals()使用的条件,compareTo()也要用 这样的compareTO()的比较对象,被equals()卡死了,equals()用的什么条件,compareTO()也要用
注意:必须用Arrays.sort()方法进行对象数组排序
二、comparator
实现comparator的接口
第一步、先定义一个排序规则类
实现接口,重写compare(obj1,obj2)方法
第二步、使用排序工具类进行排序
collections.sort(list,new sorted());
三、collection只能排序,Arraylist不能排序,如果又想去重,又想排序怎么办?
可以使用collections排序完,再使用LinkedHashSet去重,注意不能用HashSet去重,因为它没有迭代顺序,又会打乱排好的顺序
两种方法对比代码:
import java.util.Comparator;
public class Student /*implements Comparable<Student>*/implements Comparator<Student>{
private int age;
private String name;
private int sno;
public Student(){
}
public Student(int sno,String name,int age){
this.sno=sno;
this.age=age;
this.name=name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSno() {
return sno;
}
public void setSno(int sno) {
this.sno = sno;
}
public String toString(){
return "姓名:"+this.name+"年龄:"+age+"学号:"+this.sno;
}
public boolean equals(Object obj){
if(obj instanceof Student){
Student otherStudent=(Student)obj;
if(this.name.equals(otherStudent.getName())&&this.age==(otherStudent.getAge())) {
return true;
}else{
return false;
}
}else{
return false;
}
}
public int hashCode(){
return this.age*13+this.name.hashCode()*17;
}
//@Override
//public int compareTo(Student o) {
// int snoResult=new Integer(o.sno).compareTo(new Integer(this.sno));
// return snoResult;
//}
@Override
public int compare(Student o1, Student o2) {
int snoResult=new Integer(o1.sno).compareTo(new Integer(o2.sno));
return snoResult;
}
/*public int compareTo(Object o) {
Student otherStudent=(Student)o;
int Nameresult=new Integer(this.sno).compareTo(otherStudent.getSno());
return Nameresult;
}*/
//compareable的用法 数组实际上是分为普通数组和对象数组两类的使用情况 在组类中使用Array.sort()方法时
//comparator是在不修改类定义的前提下 对对象进行排序、
/*public int compare(Student o1, Student o2) {
int snoResult=new Integer(o1.sno).compareTo(new Integer(o2.sno));
return snoResult;
}*/
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
public class Test {
public static void main(String[] args) {
List <Student> set=new ArrayList<Student>();
Student a=new Student(1,"甲",20);
Student a0=new Student(1,"甲",20);//去重
Student a1=new Student(2,"乙",20);
Student a2=new Student(3,"丙",20);
set.add(a);
set.add(a0);
set.add(a1);
set.add(a2);
Collections.sort(set, new Student());
for(Student temp:set){
System.out.println(temp+" ");
}
//在hashSet中不能用comparable进行排序,只能在ThreeSet中进行排序
}
}