集合框架之TreeSet集合的自定義物件
阿新 • • 發佈:2018-12-19
package myclass; import java.util.; / 往TreeSet集合中儲存自定義物件學生 向按照學生的年齡進行排序。
需要實現Compareable 介面。
當主要條件相同時,就需要比較次要條件
*/
class Student implements Comparable//該介面強制讓學生具備比較性
{
private String name;
private int age;
Student(String name,int age)
{
this.name = name;
this.age = age;
}
public int compareTo(Object obj)
{
if(!(obj instanceof Student))
throw new RuntimeException(“不是學生”);
Student s = (Student)obj;
if(this.age > s.age)
return 1;
if(this.age == s.age)
{
return this.name.compareTo( s.name);
}
else
return -1;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
}
class TreeSetTest { public static void main(String[] args) { TreeSet ts = new TreeSet();
ts.add(new Student("zhangsan",30)); ts.add(new Student("lisi",25)); ts.add(new Student("wuliu",23)); ts.add(new Student("wuliu0",23)); ts.add(new Student("zhansan",21)); Iterator it = ts.iterator(); while(it.hasNext()) { Student stu = (Student)it.next(); System.out.println(stu.getName() + " ::" + stu.getAge()); } }
}