【java】TreeSet的自然排序

package collection;
/*
 * TreeSet的自然排序
 * 向TreeSet类对象中添加自定义的类对象,会报错classCastException 类型转换异常 ,因为不能转换成 Comparabel的实现类。
 * 步骤:
 * 1,自定义类实现Comparable接口       Person implements Comparable
 * 2,自定义类除了需要重写hashCode()和equals()方法外,还需要重写compareTo(Object obj)方法,在方法中自定义排序规则。
 */
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

import org.junit.Test;

public class TestTreeSet {
	public static void main(String[] args) {

	}

	@Test
	public void test1() {
		Set ts = new TreeSet();
		ts.add(new Person(1001, "张三", 23));
		ts.add(new Person(1002, "李四", 24));
		ts.add(new Person(1001, "王五", 24));
		ts.add(new Person(1001, "aa", 24));
		Iterator iterator = ts.iterator();
		while (iterator.hasNext()) {
			System.out.println(iterator.next());
		}
	}
}

class Person implements Comparable {// 第一步:自定义类必须实现Comparable接口
	private int id;
	private String name;
	private int age;

	public Person() {
		super();
	}

	public Person(int id, String name, int age) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

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

	@Override
	public String toString() {
		return "person [id=" + id + ", name=" + name + ", age=" + age + "]";
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + age;
		result = prime * result + id;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Person other = (Person) obj;
		if (age != other.age)
			return false;
		if (id != other.id)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}

	public int compareTo(Object obj) {// 第二步:重写compareTo()方法,自定义排序规则
		Person p = (Person) obj;
		int result;
		result = id > p.id ? 1 : (id == p.id ? 0 : -1);
		if (result == 0) {
			result = age > p.age ? 1 : (age == p.age ? 0 : -1);
			if (result == 0) {
				result = name.compareTo(p.name);
			}
		}
		return result;
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值