TreeSet如何實現有序?

package set.test;

import java.util.TreeSet;

/**
 * 實現TreeSet存儲和取出的順序一致
 * */
public class TreeSetTest {

	public static void main(String[] args) {
		
		//首先咱們知道TreeSet底層是二叉樹算法
		TreeSet<Person> treeSet = new TreeSet<>();
		treeSet.add(new Person("小A", 17));
		treeSet.add(new Person("小B", 19));
		treeSet.add(new Person("小C", 21));
		treeSet.add(new Person("小C", 21));
		//加強for循環
		for (Person person : treeSet) {
			System.out.println(person.getName()+"..."+person.getAge());
		}
	}
}
class Person implements Comparable<Person>{
	private String name;
	private int age;
	public Person(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;
	}
	
	@Override
	public int compareTo(Person o) {
		//return compareToAge(o);
		System.out.println("進入compareTo方法");
		return compareToAge(o);
	}
	//按年齡從大到小排序
	private int compareToAge(Person o) {
		//判斷是否是自己
		if(o==this) {
			return 0;
		}
		int result = o.getAge()-this.getAge();
		if(result>0) {
			return 1;
		}else if(result<0) {
			return -1;
		}
		return 0;
	}
	//存儲和取出順序一致
	private int compareToNormal() {
		return 1;
	}
}
相關文章
相關標籤/搜索