zoukankan      html  css  js  c++  java
  • TreeSet

    1.向TreeSet中添加的元素必须是同一个类的

    2.可以按照添加进集合中的元素的指定的顺序遍历。像String,包装类等默认按照从小到大的顺序遍历

    3.当向TreeSet中添加自定义类的对象时,有两种排序方法:自然排序、定制排序

    4.自然排序:要求自定义类实现java.lang.Comparable接口并重写compareTo(Object obj),在此方法中,指名按照自定义类的那个属性进行排序

    5 向TreeSet中添加元素时,首先按照compareTo()进行比较,一旦返回0,虽然仅是两个对象属性值相同,但是程序会认为这两个对象是相同的,进而后一个对象不能添加进来。

    6 TreeSet先执行compareto方法,再执行hashcode和equals方法,所以compareTo()与hashcode()与equals()三者保持一致

    7

    package lianxi2;
    
    import java.util.Set;
    import java.util.TreeSet;
    
    import org.junit.Test;
    
    public class TestTreeSet {
    @Test
      public void testTreeSet(){
         Set set = new TreeSet();
          set.add(new Student(1001,"huhu"));         //重写了equals和hashcode方法
          set.add(new Student(1003,"gx"));
          set.add(new Student(1007,"safd"));        
          set.add(new Student(1005,"gas"));
          set.add(new Student(1005,"cxz"));        
          System.out.println(set.size());
          System.out.println(set);
      }
    }

    结果:

    5
    [Student [id=1001, name=huhu], Student [id=1003, name=gx], Student [id=1005, name=cxz], Student [id=1005, name=gas], Student [id=1007, name=safd]]

    @Override
    public int compareTo(Object o){
        if(o instanceof Student){
            Student s = (Student)o;
            //return this.name.compareTo(s.name);//按name属性从低到高排序
            //return this.id - s.id; //按id属性从小到大排序
            int i = this.id - s.id;
            if(i==0){
                return this.name.compareTo(s.name);
            }
            else{
                return i;
            }
        }
        return 0;  //如果不是Student类的对象,不能加入
    }

  • 相关阅读:
    cf359D Pair of Numbers
    cf671B Robin Hood
    [暑假集训--数位dp]hdu5787 K-wolf Number
    [暑假集训--数位dp]UESTC250 windy数
    [暑假集训--数位dp]LightOj1205 Palindromic Numbers
    [暑假集训--数位dp]LightOJ1140 How Many Zeroes?
    [暑假集训--数位dp]LightOj1032 Fast Bit Calculations
    [暑假集训--数位dp]hdu5898 odd-even number
    [暑假集训--数位dp]cf55D Beautiful numbers
    [暑假集训--数位dp]hdu3709 Balanced Number
  • 原文地址:https://www.cnblogs.com/yjtm53/p/4148887.html
Copyright © 2011-2022 走看看