treeSet实现排序两种放方法
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了treeSet实现排序两种放方法相关的知识,希望对你有一定的参考价值。
参考技术A //存入TreeSet集合中的元素是无序的,但有方法给它排序//排序方式一:让元素自身具备比较性,需元素实现Comparable接口
//核心:重写Comparable接口的方法compareTo(Object obj)
//if (tea.age == this.age) //年纪相同时再按照姓名排序!!!
// return this.name.compareTo(tea.name);
//因为String也类实现了此接口,当然就可以调用compareTo()方法
class Teacher implements Comparable
private int age;
private String name;
public Teacher(intage, String name)
this.age = age;
this.name = name;
public int getAge()
returnage;
public String getName()
return name;
@Override
public String toString()
return"Teacher [age="+ age +", name="+ name +"]";
@Override
public int compareTo(Object obj) //按照年纪排序
Teacher tea = (Teacher) obj;
if(tea.age
return-1;
if(tea.age ==this.age) //年纪相同时再按照姓名排序!!!核心
return this.name.compareTo(tea.name);
if(tea.age >this.age)
return1;
return0;
publicclassTreeSetTest1
public static voidmain(String[] args)
Teacher teac1=newTeacher(25,"lim");
Teacher teac2=newTeacher(26,"uim");
Teacher teac3=newTeacher(55,"zim");
Teacher teac4=newTeacher(55,"mim");
Teacher teac5=newTeacher(55,"cim");
TreeSet treeSet=newTreeSet();
treeSet.add(teac1);
treeSet.add(teac2);
treeSet.add(teac3);
treeSet.add(teac4);
treeSet.add(teac5);
Iterator iterator=treeSet.iterator();
while(iterator.hasNext())
Teacher t=(Teacher) iterator.next();
System.out.println(t.getName()+"的年纪是"+t.getAge());
以上是关于treeSet实现排序两种放方法的主要内容,如果未能解决你的问题,请参考以下文章