学生自动排队实例(comparactor比较器)

来源:互联网 发布:淘宝怎么提高宝贝权重 编辑:程序博客网 时间:2024/06/05 06:19

本节实现了学生自动排队实例,comparactor比较器实现了比较的方法。

1.由于实现了比较器类,所以不需要实现Comparable接口。

2.实现Comparable接口的排序叫做自然排序,利用比较器类的排序叫做客户化排序

3.可以按需定制自己的compare方法。

StudentCom类

public class StudentCom {private String name;private int height;public StudentCom(){}public StudentCom(String name,int height){this.name=name;this.height=height;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getHeight() {return height;}public void setHeight(int height) {this.height = height;}public String toString(){return "姓名"+this.name+"身高为"+this.height;}public boolean equals(Object obj){if(obj instanceof StudentCom){StudentCom stu=(StudentCom)obj;if(this.name.equals(stu.name)&&this.height==stu.height){return true;}}return false;}public int hashCode(){return name.hashCode()^height;}}
比较器类StudentComparactor

import java.util.Comparator;public class StudentComparactor implements Comparator<StudentCom> {public int compare(StudentCom stu1,StudentCom stu2){if(stu1.getName().compareTo(stu2.getName())>0){return 1;}elseif(stu1.getName().compareTo(stu2.getName())<0){return -1;}else{return stu1.getHeight()-stu2.getHeight();}//return 0;}}
测试类main

import java.util.Iterator;import java.util.SortedSet;import java.util.TreeSet;public class main {public static void main(String[] args){SortedSet<StudentCom> set=new TreeSet<StudentCom>(new StudentComparactor());StudentCom a=new StudentCom("a",167);StudentCom b=new StudentCom("b",145);StudentCom c=new StudentCom("c",189);StudentCom d=new StudentCom("d",179);StudentCom e=new StudentCom("a",189);set.add(a);set.add(b);set.add(c);set.add(d);set.add(e);Iterator it=set.iterator();while(it.hasNext()){System.out.println(it.next());}}}
运行结果:



0 0