TreeSet存储自定义对象,并对对象排序的两种方式

想有一个自定义对象,先搞一个Student类。

//Student.java
package com.huowolf;


public class Student implements Comparable{
		private String name;
		private int age;
		
		public Student(String name, int age) {
			this.name = name;
			this.age = age;
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

		public int getAge() {
			return age;
		}

		public void setAge(int age) {
			this.age = age;
		}
		
		public int compareTo(Object obj) {
			if(!(obj instanceof Student))
				throw new RuntimeException("不是学生对象");
			
			Student stu=(Student)obj;
			if(this.age>stu.age)
				return 1;
			if(this.age==stu.age)
				return this.name.compareTo(stu.name);
			return -1;
		}
		
}

 //TreeSetDemo1.java
package com.huowolf;

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



/**
 * @author huowolf
 *排序的第一种方式:让元素自身具备比较性。
 *元素需要实现Comparable接口,覆盖compareTo方法
 *这种方式也元素的自然顺序
 */
public class TreeSetDemo {

	public static void main(String[] args) {
		TreeSet<Object> ts= new TreeSet<Object>();
		ts.add(new Student("lisi01",22));
		ts.add(new Student("lisi02",20));
		ts.add(new Student("lisi03",18));
		ts.add(new Student("lisi04",25));
		ts.add(new Student("lisi05",18));
		
		Iterator it = ts.iterator();
		while(it.hasNext())	{
			Student stu =	(Student) it.next();
			System.out.println("姓名:"+stu.getName()+" 年龄:"+stu.getAge());
		}

	}

}

//TreeSetDemo2.java

package com.huowolf;

import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;


/**
 * @author huowolf
 *排序的第二种方式:当元素自身不具备比较性时,让集合自身具备比较性。
 *在集合初始化时,指定比较器。
 */
public class TreeSetDemo2 {

	public static void main(String[] args) {
		TreeSet<Object> ts= new TreeSet<Object>(new MyCompare());
		ts.add(new Student("lisi01",22));
		ts.add(new Student("lisi02",20));
		ts.add(new Student("lisi03",18));
		ts.add(new Student("lisi04",25));
		ts.add(new Student("lisi02",27));
		
		Iterator it = ts.iterator();
		while(it.hasNext())	{
			Student stu =	(Student) it.next();
			System.out.println("姓名:"+stu.getName()+" 年龄:"+stu.getAge());
		}

	}

}


class MyCompare implements Comparator	{
	public int compare(Object o1,Object o2)	{
		Student s1 = (Student) o1;
		Student s2 = (Student) o2;
		int num = s1.getName().compareTo(s2.getName());
		if(num==0)
			 //return s1.getAge()-(s2.getAge());
			return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
		return num;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值