TreeSet类

1.自然排序

2.存储对象

对象实现Comparable接口

 1 import java.util.Iterator;
 2 import java.util.TreeSet;
 3 
 4 public class TreeSetDemo {
 5     public static void main(String[] args){
 6         TreeSet<Student> ts =new TreeSet<Student>();
 7         ts.add(new Student(21,"zhangsan"));
 8         ts.add(new Student(29,"lisi"));
 9         ts.add(new Student(23,"zhangsan"));
10         Iterator<Student> it =ts.iterator();
11         while(it.hasNext()){
12             Student s = it.next();
13             System.out.println(s.getAge()+"..."+s.getName());
14         }
15         
16     }
17 }
18 class Student implements Comparable<Student>{
19     public Student(int age, String name) {
20         super();
21         this.age = age;
22         this.name = name;
23     }
24     public int getAge() {
25         return age;
26     }
27     public void setAge(int age) {
28         this.age = age;
29     }
30     public String getName() {
31         return name;
32     }
33     public void setName(String name) {
34         this.name = name;
35     }
36     private int age;
37     private String name;
38     @Override
39     public int compareTo(Student s) {
40         int num = this.name.compareTo(s.name);
41         if(num==0)
42             return new Integer(this.age).compareTo(new Integer(s.age));
43         return num;
44     }
45     
46 }

实现Comparator接口

 1 import java.util.Comparator;
 2 import java.util.Iterator;
 3 import java.util.TreeSet;
 4 
 5 public class TreeSetDemo {
 6     public static void main(String[] args){
 7         TreeSet<Student> ts =new TreeSet<Student>(new MyComp());
 8         ts.add(new Student(21,"zhangsan"));
 9         ts.add(new Student(29,"lisi"));
10         ts.add(new Student(23,"wangwu"));
11         Iterator<Student> it =ts.iterator();
12         while(it.hasNext()){
13             Student s = it.next();
14             System.out.println(s.getAge()+"..."+s.getName());
15         }
16         
17     }
18 }
19 class Student  {
20     public Student(int age, String name) {
21         super();
22         this.age = age;
23         this.name = name;
24     }
25     public int getAge() {
26         return age;
27     }
28     public void setAge(int age) {
29         this.age = age;
30     }
31     public String getName() {
32         return name;
33     }
34     public void setName(String name) {
35         this.name = name;
36     }
37     private int age;
38     private String name;
39     
40 }
41 class MyComp implements Comparator<Student>{
42 
43     @Override
44     public int compare(Student o1, Student o2) {
45         int num = o1.getName().compareTo(o2.getName());
46         if(num==0)
47             return new Integer(o1.getAge()).compareTo(new Integer(o2.getAge()));
48         return num;
49 
50     }
51     
52 }

3.二叉树

4.TreeSet练习

原文地址:https://www.cnblogs.com/malinkang/p/2580250.html