TreeSet与TreeMap

                                 TreeSet与TreeMap



  TreeSet:


1.TreeSet优点可以初系统自己的排序外,还可以自定义排序;(Comparable与Comparator)

2.在添加数据时排序;

3.缺点:添加了的数据不能更改;(因为2,所以在你改变了数据后,数据顺序亦不会在改变)

4.具有Tree的特性:排序,Set的特性:数据不能重复;

5.一般我们把数据设为修饰final。防止数据被修改或重复;

------------------------------------------------------------------
 TreeMap:

1.具有Tree特点:对键值(key)排序,Map特性:存取key,value;

2.在添加数据时排序;

3.缺点:添加了的数据不能更改;(因为2,所以在你改变了数据后,数据顺序亦不会在改变)

----------------------------------------------------------------------------
用例:
public class haha implements Comparable<haha>{
    private String name;

    public haha(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    @Override
    public int compareTo(haha another) {
        return this.name.length()==another.getName().length()?0:this.name.length               ()>another.getName().length()?1:-1;
    }
   }

public class xixi implements Comparable<xixi>{
    private String name;

    public xixi(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    @Override
    public int compareTo(xixi another) {
        return this.name.length()==another.getName().length()?0:this.name.length               ()>another.getName().length()?1:-1;
    }
   }

public  void test(){

         haha h=new haha("xixiqasd");     
         haha h1=new haha("hehe");
         haha h2=new haha("hehwweq");
         haha h3=new haha("hehqwee");
         TreeSet<haha> t=new TreeSet();
         t.add(h);
         t.add(h1);
         t.add(h2);
         t.add(h3);


         xixi x=new xixi("xixiqasd","dajksh");     
         xixi x1=new xixi("hAsAS","dajksh");
         xixi x2=new xixi("hehsAwweq","dajksh");
         xixi x3=new xixi("hehqwee","dajksh");
         TreeMap<xixi> t=new TreeMap();
         t.add(x);
         t.add(x1);
         t.add(x2);
         t.add(x3);

        
}

猜你喜欢

转载自blog.csdn.net/silently_frog/article/details/79077301