自定义的对象存放在TreeSet树集合中

来源:互联网 发布:知乎 编 专栏 编辑:程序博客网 时间:2024/05/16 12:28
import java.util.*;public class TreeSetTest2{public static void main(String args[]){TreeSet tree=new TreeSet(new MComparator());Student stu1=new Student(90);Student stu2=new Student(85);Student stu3=new Student(95);Student stu4=new Student(88);tree.add(stu1);tree.add(stu2);tree.add(stu3);tree.add(stu4);Iterator i=tree.iterator();while(i.hasNext()){Student s=(Student)i.next();System.out.print(s.score+" ");}}}class Student{int score;public Student(int score){this.score=score;}}//集合中存放的为对象,自定义的对象,java默认的排序方法无法对其进行排序,出现异常,因而需要自己定义排序法则!class MComparator implements Comparator{@Overridepublic int compare(Object o1, Object o2){// TODO Auto-generated method stubStudent s1=(Student)o1;Student s2=(Student)o2;if(s1.score>s2.score)return 1;else if(s1.score<s2.score)return -1;else return 0;}}

0 0
原创粉丝点击