JAVA Set集合 TreeSet

想要实现Set集合有序,被排序的对象需要实现Compareable接口

定义类Person

public class Person implements Comparable{
	int num;
	int age;
	String name;
	
	//创建构造方法
	public Person(int num, int age, String name) {
		super();
		this.num = num;
		this.age = age;
		this.name = name;
	}

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

	public int compareTo(Object object){
		Person person;
		if(object instanceof Person){
			person = (Person)object;//如果传入参数是Person的实例,则强制转换
		}else {
			return -1;
		}
		int diff = person.age - age;
		if(diff!=0)
		return diff/Math.abs(diff);
		
		return 0;
	}
	
}

 注意:如果加入null会有nullpointException空指针异常

因为每加入一个对象自动调用compareTo方法,使用TreeSet不能加入空指针

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


public class guess{
	public static void main(String[] args) {
		Person person1 = new Person(1, 20, "张三");
		Person person2 = new Person(2, 10, "阿财");
		Person person3 = new Person(3, 27, "小刘");
		
		Set aSet = new TreeSet();
		
		aSet.add(person1);
		aSet.add(person2);
		aSet.add(person3);
                //aSet.add(null);
		
		Iterator iterator = aSet.iterator(); 
		while(iterator.hasNext()){
			System.out.println(iterator.next());
		}
		
	}

}

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

扫码关注云+社区

领取腾讯云代金券