比较整集

时间:2019-08-31
本文章向大家介绍比较整集,主要包括比较整集使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

HashSet集合中,数据结构是哈希表。线程非同步。 其保证元素唯一性的原理,是判断元素的HashCode值是否相同。

如果相同,还会继续判断元素的equals方法,是否为true。


TreeSet()构造方法摘要:

TreeSet()   :构造一个新的空Set,该Set 根据元素的自然排序进行排序。  (也就是 Comparable的  compareTo方法)      《第一种》

TreeSet(Comparator ):构造一个新的空TreeSet,它根据比较器进行排序。        《第二种》

TreeSet集合当中,所存元素为自己定义的,需要自己定义比较性。以 Student为例-----getName---getAge

方式:  让Student 实现 Comparable  ---- 然后覆盖它的 comepareTo方法,定义自己需要的比较功能。   (第一种排序)

import java.util.*;
public class Practice_1 {    
    public static void main(String[] args) {
        TreeSet<Student> ts = new TreeSet<Student>();
        ts.add(new Student("java001",10));
        ts.add(new Student("java004",40));
        ts.add(new Student("java003",30));
        ts.add(new Student("java002",20));
        ts.add(new Student("java008",20));
        
        Iterator<Student> it = ts.iterator();
        while(it.hasNext())
        {
            Student stu = it.next();
            sop(stu.getName()+"...."+stu.getAge());
        
        }
    }
    public static void sop(Object obj)
    {
        System.out.println(obj);
    }
}

class Student implements Comparable
{
    private String name;
    private int age;
    Student(String name, int age)
    {
        this.name = name;
        this.age = age;
    }
    public String getName()
    {
        return name;
    }
    public int getAge()
    {
        return age;
    }
    public int compareTo(Object obj)
    {
        if(!(obj instanceof Student))
        {
            throw new RuntimeException("不是学生对象");
        }
        Student s = (Student)obj;
        if(this.age > s.age)
        {
            return 1;
        }
        if(this.age == s.age)
        {
            return this.name.compareTo(s.name);
        }
        return -1;
    }
}

元素自身不具备比较性时,或者具备的比较性不是所需要的,这时候需要让集合自身具备比较性。   (第二种排序)

在集合初始化时候,就有比较方式。 定义一个比较器,将比较器对象作为参数传递给TreeSet集合的构造函数。

如下:   将比较器传入TreeSet()构造函数进行比较即可。

class MyCompare implements Comparator
{
    public int compare(Object o1,Object o2)
    {
        Student s1 = (Student)o1;
        Student s2 = (Student)o2;
        int num =s1.getName().compareTo(s2.getName());
        if(num == 0)
        {
            return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
        }
        return num;
    }
}

原文地址:https://www.cnblogs.com/zxl1010/p/11440434.html