Set 集合

一、HashSet按照Hash算法存储集合元素(hashCode方法获取hashCode值,根据hashCode值获取元素位置,通过equals判断对象是否相等并且hashCode值是否相等),因此具有很好的查找和存取的性能。排列顺序不固定,非线程安全,集合元素可以为空,不允许重复。

二、LinkedHashSet(HashSet子类)链表维护元素次序(因此插入,删除性能低于HashMap),迭代访问Set里的全部元素性能较好,不允许重复。

三、iterator(foreach)迭代某个集合时,迭代内集合不可以remove操作集合本身,但是可以通过iterator的remove方法移除集合元素。

四、TreeSet(SortedSet) 按照自然排序和定制排序排序。默认采用自然排序(升序)。对象添加到TreeSet时,该对象必须实现Comparable接口,否则ClassCastException异常。

五、TreeSet结合判断两个对象是否相等的唯一标准是:两个对象通过compareTo方法比较是否返回0。、

六、TreeSet自然排序,元素必须实现Comparable接口  TreeSet ts = new TreeSet();  ts.add(new Student());  Student 类必须实现Comparable;

//对象类
public class Father implements Comparable<Father> {
    private String  name;
    private Integer age;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public Father() {
        System.out.println("父类无参构造");
    }
    public Father(String name, Integer age) {
        super();
        this.name = name;
        this.age = age;
    }
    @Override
    public String toString() {
        return "Father [name=" + name + ", age=" + age + "]";
    }
    
    @Override
    public int compareTo(Father o) {
        Father father = o;
        return this.name.compareTo(father.getName());
    }

}

//验证排序  
        @Test
    public void method2(){
        TreeSet<Father> fathers = new TreeSet<>();
        fathers.add(new Father("a",10));
        fathers.add(new Father("c",10));
        fathers.add(new Father("b",10));
        for (Father father : fathers) {
            System.out.println(father);
        }
    }    
输出结果为
Father [name=a, age=10]
Father [name=b, age=10]
Father [name=c, age=10]
TreeSet自然排序

相关文章:

  • 2021-11-18
  • 2022-01-30
  • 2022-02-01
  • 2022-02-27
  • 2021-10-06
  • 2021-12-06
  • 2022-03-09
猜你喜欢
  • 2021-04-18
  • 2021-06-02
  • 2021-12-08
  • 2021-11-23
  • 2022-01-21
  • 2022-01-03
  • 2021-10-07
相关资源
相似解决方案