栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

4.Set集合

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

4.Set集合

1. Set集合的概述和特点

Set集合特点

  • 不包含重复元素的集合
  • 没有带索引的方法,所以不能使用普通for循环遍历
package SetStudy.study01;

import java.util.HashSet;
import java.util.Set;


public class SetDemo {
    public static void main(String[] args) {
        //创建集合对象
        Set set = new HashSet();
        //添加集合元素
        set.add("hello");
        set.add("world");
        set.add("java");
        //不包含重复元素的集合
        set.add("world");//输出只有一个world
        //遍历
        for (String s:set){
            System.out.println(s);
        }
    }
}
2.哈希值

哈希值:是JDK根据对象的地址或者字符串或者数字算出来的int类型的数值。

Object类中有一个方法可以获取对象的哈希值

  • public int hashCode():返回对象的哈希码值

对象的哈希值特点

  • 同一个对象多次调用hashCode()方法返回的哈希值是相同的
  • 默认情况下,不同对象的哈希值是不同的,而重写hashCode()方法,可以实现让不同对象的哈希值相同。
package SetStudy.study02;

public class hashDemo {
    public static void main(String[] args) {
        student s = new student("明明",19);
        //同一个对象多次调用hashCode()返回的值是相同的
        System.out.println(s.hashCode());//460141958
        System.out.println(s.hashCode());//460141958
        System.out.println("============");

        student s1 = new student("明明",19);
        //默认情况下,不同对象调用hashCode()返回的值是不同的
        //通过方法重写,可以实现不同对象调用hashCode()返回的值相同
        System.out.println(s1.hashCode());//1163157884
        System.out.println("============");

        System.out.println("hello".hashCode());//99162322
        System.out.println("world".hashCode());//113318802
        System.out.println("java".hashCode());//3254818

        System.out.println("world".hashCode());//113318802
        System.out.println("============");

        System.out.println("重地".hashCode());//1179395
        System.out.println("通话".hashCode());//1179395
        System.out.println("安徽".hashCode());//750932
    }
}
3.HashSet集合概述和特点

HashCode集合特点

  • 底层数据结构是哈希表
  • 对集合的迭代顺序不作任何保证,也就是说不保证存储和取出来的元素顺序一致。
  • 没有带索引的方法,所以不能使用普通的for循环遍历
  • 由于是Set集合,所以是不包含重复元素的集合
package SetStudy.study03;
import java.util.HashSet;

public class HashSetDemo {
    public static void main(String[] args) {
        HashSet hs = new HashSet();
        hs.add("java");
        hs.add("world");
        hs.add("hello");

        hs.add("world");
       //遍历
        for (String s:hs){
            System.out.println(s);
        }
        
    }
}
4.HashSet集合保证元素唯一性源码分析

HashSet集合添加一个元素的过程:

HashSet集合存储元素:

  • 要保证元素一致性,需要重写hashCode()和equals()
5.常见数据结构之哈希表

哈希表

  • JDK8之前,底层采用数组+链表实现,可以说一个元素为链表的数组。
  • JDK8以后,在长度较长的时候,底层实现了优化
6.案例

案例:HashSet集合存储学生对象并遍历

需求:创建一个存储学生对象的集合,存储多个学生对象,使用程序实现在控制台遍历该集合。

要求:学生对象的成员变量值相同,我们就认为是同一个对象

思路:

  1. 定义学生类
  2. 创建HashSet集合对象
  3. 创建学生对象
  4. 把学生添加到集合
  5. 遍历集合(增强for)
  6. 在学生类中重写两个方法
  • hashCode()和equals()
  • 自动生成即可
//student类
package SetStudy.study04;

public class student {
    private String name;
    private int age;
    private String sex;

    public student() {
    }

    public student(String name, int age, String sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }
    public void print(student s){
        System.out.println("姓名:"+s.getName()+"; 年龄:"+s.getAge()+"; 性别:"+s.getSex());
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        student student = (student) o;

        if (age != student.age) return false;
        if (name != null ? !name.equals(student.name) : student.name != null) return false;
        return sex != null ? sex.equals(student.sex) : student.sex == null;
    }

    @Override
    public int hashCode() {
        int result = name != null ? name.hashCode() : 0;
        result = 31 * result + age;
        result = 31 * result + (sex != null ? sex.hashCode() : 0);
        return result;
    }
}

//studentDemo
package SetStudy.study04;

import java.util.HashSet;


public class studentDemo {
    public static void main(String[] args) {
        //创建student对象
        student s = new student("小明",19,"男");
        student s5 = new student("小明",19,"男");
        student s1 = new student("小梁",18,"女");
        student s2 = new student("小李",18,"女");

        //创建HashSet对象
        HashSet hashSet = new HashSet();
        hashSet.add(s);
        hashSet.add(s1);
        hashSet.add(s2);
        hashSet.add(s5);

        //遍历
        for (student s3:hashSet){
            s3.print(s3);
        }
        
    }
}
7.linkedHashSet集合概述和特点

linkedHashSet集合特点

  • 哈希表和链表实现的Set接口,具有可预测的迭代次序
  • 由链表保证元素有序,也就是说元素的存储和取出顺序是一致的。
  • 由哈希表保证元素唯一,也就是说没有重复元素

linkedHashSet集合练习

  • 存储字符串并遍历
package SetStudy.study05;

import java.util.linkedHashSet;


public class linkedHashSetDemo {
    public static void main(String[] args) {
        //创建linkedHashSet对象
        linkedHashSet linkedHashSet = new linkedHashSet();
        //添加元素
        linkedHashSet.add("hello");
        linkedHashSet.add("world");
        linkedHashSet.add("java");

        linkedHashSet.add("hello");
        //遍历
        for (String s:linkedHashSet){
            System.out.println(s);
        }
        
    }
}
8.TreeSet集合概述和特点

TreeSet集合特点

  • 元素有序,这里的顺序不是指存储和取出的顺序,而是按照一定的规则进行排序,具体排序方法取决于构造方法

    • TreeSet():根据元素的自然排序进行排序
    • TreeSet(Comparator comparator):根据指定的比较器进行排序
  • 没有带索引的方法,所以不能使用普通for循环遍历

  • 由于是Set集合,所以不包含重复元素的集合

TreeSet集合练习

  • 存储整数并遍历
package SetStudy.study06;

import java.util.TreeSet;


public class TreeSetDemo {
    public static void main(String[] args) {
        //创建对象
        TreeSet treeSet = new TreeSet();//Integer是int的包装类对象
        //添加元素
        treeSet.add(10);
        treeSet.add(40);
        treeSet.add(30);
        treeSet.add(20);
        treeSet.add(50);

        treeSet.add(30);
        //遍历
        for (Integer i :treeSet){
            System.out.println(i);
        }
//        结果:
//        10
//        20
//        30
//        40
//        50
    }
}
9.自然排序Comparable的使用

需求:存储学生对象并遍历,创建TreeSet集合使用无参构造方法

要求:按照年龄从大到校排序,年龄相同时,按照姓名的字母顺序排序

//student类
package SetStudy.study07;

public class student implements Comparable{
    private String name;
    private int age;

    public student() {
    }

    public student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public int compareTo(student s) {
//        return 0;//存储第一个后,其他元素在存储的时候会默认跟第一个元素相同不添加
//        return 1;//按照升序进行存储
//        return -1;//按照降序进行存储
//        按照年龄从大到小排序
        int num = this.age - s.age;//this.age就是s2,s.age就是s1------以s2和s1比较时为例
//        int sum = s.age - this.age;//从小到大排序
//        年龄相同时,按照姓名的字母顺序排序
        int num2 = num==0?this.name.compareTo(s.name):num;
        return num2;

    }
}

package SetStudy.study07;

import java.util.TreeSet;


public class TreeSetDemo1 {
    public static void main(String[] args) {
        //创建TreeSet对象
        TreeSet ts = new TreeSet();
        //创建学生对象
        student s = new student("xishi", 20);
        student s1 = new student("yangyuhuan", 21);
        student s2 = new student("diaochan", 23);
        student s3 = new student("wangzhaojun", 25);

        student s4 = new student("lingqingxia", 25);
        student s5 = new student("lingqingxia", 25);
        //添加元素
        ts.add(s);
        ts.add(s1);
        ts.add(s2);
        ts.add(s3);
        ts.add(s4);
        ts.add(s5);
        //遍历
        for (student ss : ts) {
            System.out.println(ss.getName() + "," + ss.getAge());
        }
    }
}

结论:

  • 用TreeSet集合存储自定义对象,无参构造方法使用的是自然排序对元素进行排序的。
  • 自然排序,就是让元素所属的类实现Comparable接口,重写compareTo(To)方法
  • 重写方法时,一定要注意排序规则必须按照要求的主要条件和次要条件来写。
10.比较器排序Comparator的使用
  • 存储学生对象并遍历,创建TreeSet集合使用带参构造方法
  • 要求:按照年龄从小到大排序,年龄相同时,按照姓名的字母顺序排序
//student类
package SetStudy.study08;

public class student {
    private String name;
    private int age;

    public student() {
    }

    public student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

package SetStudy.study08;

import java.util.Comparator;
import java.util.TreeSet;


public class TreeSetDemo {
    public static void main(String[] args) {
        TreeSet ts = new TreeSet(new Comparator() {
            @Override
            public int compare(student o1, student o2) {
//                return 0;
                int num = o1.getAge() - o2.getAge();
                int num2 = num==0?o1.getName().compareTo(o2.getName()):num;
                return num2;
            }
        });
        //创建学生对象
        student s = new student("xishi", 20);
        student s1 = new student("yangyuhuan", 21);
        student s2 = new student("diaochan", 23);
        student s3 = new student("wangzhaojun", 25);

        student s4 = new student("lingqingxia", 25);
        student s5 = new student("lingqingxia", 25);
        //添加元素
        ts.add(s);
        ts.add(s1);
        ts.add(s2);
        ts.add(s3);
        ts.add(s4);
        ts.add(s5);
        //遍历
        for (student ss : ts) {
            System.out.println(ss.getName() + "," + ss.getAge());
        }
    }
}

结论:

  • 用TreeSet集合存储自定义对象,带参构造方法使用的是比较器排序对元素进行排序的
  • 比较器排序,就是让集合构造方法接收Comparator的实现类对象,重写compare(T o1,T o2)方法。
  • 重写方法时,一定要注意排序规则必须按照要求的主要条件和次要条件来写。
11.案例:成绩排序

需求:用TreeSet集合存储多个学生信息(姓名,语文成绩,数学成绩),并遍历该集合。

要求:按照总分从高到低出现

//student类
package SetStudy.study09;

public class student implements Comparable{
    private String name;
    private int ChineScores;
    private int MathScores;

    public student() {
    }

    public student(String name, int chineScores, int mathScores) {
        this.name = name;
        ChineScores = chineScores;
        MathScores = mathScores;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getChineScores() {
        return ChineScores;
    }

    public void setChineScores(int chineScores) {
        ChineScores = chineScores;
    }

    public int getMathScores() {
        return MathScores;
    }

    public void setMathScores(int mathScores) {
        MathScores = mathScores;
    }

    @Override
    public int compareTo(student o) {
        int num1 = this.ChineScores + this.MathScores;
        int num2 = o.ChineScores + o.MathScores;
        int num3 = num2 - num1;
        int num4 = num3 == 0 ? this.ChineScores-o.getChineScores() : num3;
        int num5 = num4 == 0? this.name.compareTo(o.name):num4;
        return num5;
    }
}

package SetStudy.study09;

import java.util.TreeSet;


public class studentDemo {
    public static void main(String[] args) {
        //创建集合对象
        TreeSet treeSet = new TreeSet();
        //创建学生对象
        student s1 = new student("小明",90,100);
        student s2 = new student("小梁",100,100);
        student s3 = new student("小李",70,60);

        student s4 = new student("明明",90,100);
        //集合对象添加元素
        treeSet.add(s1);
        treeSet.add(s2);
        treeSet.add(s3);
        treeSet.add(s4);

        //遍历
        for (student s:treeSet){
            System.out.println("姓名:"+s.getName()+", 语文成绩:"+s.getChineScores()+", 数学成绩:"+s.getMathScores()+", 总分:"+(s.getChineScores()+s.getMathScores()));
        }
    }
}
12. 案例:不重复的随机数

需求:编写一个程序,获取10个1-20之间的随机数,要求随机数不能重复,并在控制台输出。

package SetStudy.study09;

import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.TreeSet;


public class randomDemo {
    public static void main(String[] args) {
        //创建random对象
        Random random = new Random();
        //创建set集合对象
//        Set set = new HashSet();//结果不排序
        TreeSet set = new TreeSet();//结果排序
        //判断集合长度是否大于10
        while (set.size()<10){
            //产生随机数并添加到集合
            int i = random.nextInt(20) + 1;
            set.add(i);
        }
        //遍历集合
        for (Integer s:set){
            System.out.println(s);
        }
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/325067.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号