仅仅是使用方法,非源码分析。
1 public class Test { 2 3 public static void main(String[] args) { 4 TreeSet<String> treeSet=new TreeSet<>(); 5 treeSet.add("Se"); 6 treeSet.add("Ald"); 7 treeSet.add("Boo"); 8 treeSet.add("CC"); 9 Iterator<String> iterator=treeSet.iterator(); 10 while (iterator.hasNext()) { 11 String string = (String) iterator.next(); 12 System.out.println(string); 13 } 14 } 15 16 }
输出:
Ald
Boo
CC
Se
使用TreeSet集合时,元素必须实现Comparable接口。
1 public class Person implements Comparable<Person> { 2 private String name; 3 private int age; 4 5 public Person() { 6 // TODO Auto-generated constructor stub 7 } 8 9 public Person(String name, int age) { 10 this.name = name; 11 this.age = age; 12 } 13 14 public String getName() { 15 return name; 16 } 17 18 public void setName(String name) { 19 this.name = name; 20 } 21 22 public int getAge() { 23 return age; 24 } 25 26 public void setAge(int age) { 27 this.age = age; 28 } 29 30 @Override 31 public String toString() { 32 // TODO Auto-generated method stub 33 return "name:" + getName() + " age:" + getAge(); 34 } 35 36 /** 37 * 升序排列 38 */ 39 @Override 40 public int compareTo(Person person) { 41 // TODO Auto-generated method stub 42 if (this.getAge() > person.getAge()) { 43 return 1; 44 } else if (this.getAge() == person.getAge()) { 45 return 0; 46 } else { 47 return -1; 48 } 49 } 50 51 }
测试类:
1 public class Test { 2 3 public static void main(String[] args) { 4 // TODO Auto-generated method stub 5 TreeSet<Person> tSet = new TreeSet<>(); 6 tSet.add(new Person("shldom", 23)); 7 tSet.add(new Person("tom", 12)); 8 tSet.add(new Person("woa", 45)); 9 tSet.add(new Person("moe", 87)); 10 Iterator<Person> iterator=tSet.iterator(); 11 while(iterator.hasNext()){ 12 System.out.println(iterator.next()); 13 } 14 } 15 16 }
输出结果:
name:tom age:12
name:shldom age:23
name:woa age:45
name:moe age:87