Java TreeSet类

一.TreeSet类中的元素必须是可“排序”的,所以必须实现接口implements Comparable类,重写compare()方法;

package ch3;

public class Student implements Comparable {
    @Override
	public int compareTo(Object o) {
		// TODO Auto-generated method stub
    	Student s =(Student)o;
    	
		return age-s.age;
	}
	private int age;
    private String name;
    Student(int num,String name)
    {
    	this.age =num;
    	this.name =name;
    }
	@Override
	public boolean equals(Object o) {
		// TODO Auto-generated method stub
		Student s =(Student)o;
		return  age ==s.age&&name.equals(s.name);
	}
	@Override
	public int hashCode() {
		// TODO Auto-generated method stub
		return age*name.hashCode();
	}
	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return "age:" +age+"name:"+name;
					}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
    
}




package ch3;

import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

public class TreeSetText {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Set ts = new TreeSet();
		Student s1 = new Student(18,"zhj");
		Student s2 = new Student(25,"zyj");
		Student s3 = new Student(28,"xml");
		Student s4 = new Student(18,"zah");
		Student s5 = new Student(18,"zah");//没有s4,s5
		ts.add(s1);
		ts.add(s2);
		ts.add(s3);
		ts.add(s4);
		ts.add(s5);
		
		Iterator in = ts.iterator();
		while(in.hasNext())
		{
			System.out.println(in.next());
		}

	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值