TreeSet的使用

TreeSet:可以按照添加元素的指定属性进行排序(比较)
TreeSet需要添加相同数据类型的元素(比较)

对于自然排序,Comparable 比较两个对象是否相等就不再是通过equals进行比较了,而是通过compareTo进行比较
对于定制排序,Comparator 比较两个对象是否相等就不再是通过equals进行比较了,而是通过compare进行比较

public class TreeSetDemo {
	public static void main(String[] args) {
		TreeSet ts = new TreeSet();
		//自然排序
		ts.add(1);
		ts.add(20);
		ts.add(5);
		ts.add(12);
		ts.add(23);
		System.out.println(ts);
	}
}

自定义类实现Comparable接口,进行自然排序

public class TreeSetDemo {
	public static void main(String[] args) {
		TreeSet<User> ts2 = new TreeSet<User>();
		//自然排序
		ts2.add(new User("1","Jack"));
		ts2.add(new User("2","Rose"));
		ts2.add(new User("3","Tom"));
		ts2.add(new User("4","Jerry"));
		ts2.add(new User("5","Tony"));
		//根据id进行排序
		System.out.println(ts2);
	}
}
class User implements Comparable<User>{
	private String uid;
	private String name;
	public String getUid() {
		return uid;
	}
	public void setUid(String uid) {
		this.uid = uid;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public User(String uid, String name) {
		super();
		this.uid = uid;
		this.name = name;
	}
	public User() {
		super();
	}
	
	@Override
	public String toString() {
		return "User [uid=" + uid + ", name=" + name + "]";
	}
	@Override
	public int compareTo(User u) {
		// TODO Auto-generated method stub
		return this.uid.compareTo(u.uid);
	}
}

自定义类实现Comparator接口,进行定制排序
如果排序规则只使用一次,可以直接使用匿名内部类,如果排序规则使用多次,可以写一个实现类传进去

public class TreeSetDemo {
	public static void main(String[] args) {
		//先按照id进行排序,如果id一致,再按照name降序
		TreeSet<User> ts = new TreeSet<>(new Comparator<User>() {

			@Override
			public int compare(User o1, User o2) {
				if(o1.getUid().compareTo(o2.getUid())!=0) {
					return o1.getUid().compareTo(o2.getUid());
				}else {
					return o1.getName().compareTo(o2.getName());
				}
			}
			
		});
		ts.add(new User("1","Jack"));
		ts.add(new User("1","Tom"));
		ts.add(new User("1","Rose"));
		ts.add(new User("4","Jerry"));
		ts.add(new User("5","Tony"));
		System.out.println(ts);
	}
}
class User{
	private String uid;
	private String name;
	public String getUid() {
		return uid;
	}
	public void setUid(String uid) {
		this.uid = uid;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public User(String uid, String name) {
		super();
		this.uid = uid;
		this.name = name;
	}
	public User() {
		super();
	}
	
	@Override
	public String toString() {
		return "User [uid=" + uid + ", name=" + name + "]";
	}
}

你可能感兴趣的:(JavaSE)