集合框架之TreeSet集合的自定义对象

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());
      }
 }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值