从零学Java Set集合

Java Set集合

文章目录

  • Java Set集合
    • 1 Set 集合
    • 2 Set实现类
      • 2.1 HashSet【重点】
      • 2.2 LinkedHashSet
      • 2.3 TreeSet
    • 3 Comparator 自定义比较器

1 Set 集合

特点:无序无下标、元素不可重复。

方法:全部继承自Collection中的方法。

常用方法

public class TestSet01 {public static void main(String[] args) {//创建集合Set<String> set = new HashSet<>();//1 添加set.add("苹果");set.add("香蕉");set.add("西瓜");set.add("菠萝");set.add("桃子");set.add("榴莲");//不能添加重复元素//set.add("苹果");System.out.println("元素个数: "+set.size());System.out.println("打印: "+set);//2 删除//2.1 删除单个元素//set.remove("西瓜");//2.2 清空//set.clear();//3 遍历//3.1 增强forfor (String s : set) {System.out.println(s);}//3.2 迭代器Iterator<String> it = set.iterator();while (it.hasNext()) {System.out.println(it.next());}//4 判断//4.1 判断是否存在System.out.println(set.contains("榴莲"));//4.2 判断是否为空System.out.println(set.isEmpty());}
}

2 Set实现类

2.1 HashSet【重点】

存储结构: 哈希表(数组+链表),基于hashCode、equals实现元素不重复。

在这里插入图片描述

存储过程

  1. 根据元素的hash值计算位置,如果这个位置没有元素直接加入。

  2. 如果有元素会调用equals进行确认,结果为true,拒绝后者存入,如果为false,形成链表。

常用方法:

public class TestHashSet {static class Student {String name;int age;public Student() {}public Student(String name, int age) {this.name = name;this.age = age;}@Overridepublic String toString() {return "Student{" +"name='" + name + '\'' +", age=" + age +'}';}/*重写规则:1 equals和hashCode要同时重写2 两个方法依据的属性保持一致*/@Overridepublic boolean equals(Object o) {if (this == o) return true;if (o == null || getClass() != o.getClass()) return false;Student student = (Student) o;return age == student.age && Objects.equals(name, student.name);}@Overridepublic int hashCode() {return Objects.hash(name, age);}}public static void main(String[] args) {//创建集合HashSet<Student> hashSet = new HashSet<>();//创建三个学生对象Student s1 = new Student("小明", 18);Student s2 = new Student("小红", 28);Student s3 = new Student("小白", 21);Student s4 = new Student("小白", 21);//1 添加hashSet.add(s1);hashSet.add(s2);hashSet.add(s3);hashSet.add(s4);System.out.println("元素个数: "+hashSet.size());System.out.println("打印: "+hashSet);//2 删除//2.1 删除单个元素//hashSet.remove(s3);//System.out.println("删除后: "+hashSet);//2.2 清空//hashSet.clear();//3 遍历//3.1 增强forfor (Student student : hashSet) {System.out.println(student);}//3.2 迭代器Iterator<Student> it = hashSet.iterator();while (it.hasNext()) {System.out.println(it.next());}//4 判断//4.1 判断是否存在某元素System.out.println(hashSet.contains(s1));//4.2 判断是否为空System.out.println(hashSet.isEmpty());}
}

2.2 LinkedHashSet

存储结构: 双向链表实现的HashSet,按照链表进行存储,即可保留元素的插入顺序。

常用方法: 与上方一致

LinkedHashSet<Student> set = new LinkedHashSet<>();

2.3 TreeSet

存储结构: 红黑树,基于排序实现元素不重复。

  • 对集合元素自动排序。
  • 元素的类型必须实现Comparable接口,或自定义比较器。

二叉查找树:

  1. 一个节点最多只能有两个子节点
  2. 左节点都比根节点小, 右节点都比根节点大, 没有重复的
  3. 遍历:
    • 先序遍历(根左右);
    • 中序遍历(左根右);
    • 后序遍历(左右根);

红黑树: 一种特殊的二叉平衡查找树

  1. 节点有黑色和红色
  2. 左右保证平衡

常用方法:

public class TestTreeSet {//静态内部类实现Comparable<?>接口static class Student implements Comparable<Student> {String name;int age;public Student(String name, int age) {this.name = name;this.age = age;}@Overridepublic String toString() {return "Student{" +"name='" + name + '\'' +", age=" + age +'}';}@Overridepublic int compareTo(Student o) {int n1 = this.age-o.age;int n2 = this.name.compareTo(o.name);return n1==0?n1:n2;}}public static void main(String[] args) {//创建集合TreeSet<Student> treeSet = new TreeSet<>();//创建四个元素Student s1 = new Student("小明", 16);Student s2 = new Student("小红", 21);Student s3 = new Student("aaa", 19);Student s4 = new Student("bbb", 19);//1 添加treeSet.add(s1);treeSet.add(s2);treeSet.add(s3);treeSet.add(s4);System.out.println("个数: "+treeSet.size());System.out.println("打印: "+treeSet);//2 删除//treeSet.remove(s4);//System.out.println("删除后: "+treeSet);//3 遍历//3.1 增强forfor (Student student : treeSet) {System.out.println(student);}//3.2 迭代器Iterator<Student> it = treeSet.iterator();while (it.hasNext()) {System.out.println(it.next());}//4 判断System.out.println(treeSet.contains(s4));System.out.println(treeSet.isEmpty());}
}

3 Comparator 自定义比较器

特点:

  • 元素自身提供的比较规则称为自然排序。
  • Comparator可以实现定制比较规则。
  • compare(o1,o2),如果返回值为0,则为重复元素。
  • 使用Comparator比较器,元素类型可不实现Comparable接口,并且优先级高于Comparable接口。
//创建比较器,定制比较规则
Comparator<Student> cmp = new Comparator<Student>() {@Overridepublic int compare(Student o1, Student o2) {int n1 = o1.name.compareTo(o2.name);int n2 = o1.age- o2.age;return n1==0?n2:n1;}
};
//创建集合
TreeSet<Student> treeSet = new TreeSet<>(cmp);

练习:

TreeSet实现字符串按照长度排序,如果长度相同,按照编码顺序。

eg:

public class TestComparator {public static void main(String[] args) {//练习:TreeSet实现字符串按照长度排序,如果长度相同,按照编码顺序。//匿名内部类Comparator<String> cmp = new Comparator<String>() {@Overridepublic int compare(String o1, String o2) {int n1 = o1.length()-o2.length();int n2 = o1.compareTo(o2);return n1==0?n2:n1;}};TreeSet<String> treeSet = new TreeSet<>(cmp);treeSet.add("aaaaa");treeSet.add("bbbbb");treeSet.add("aaa");treeSet.add("badssd");treeSet.add("xxxxxxxx");treeSet.add("aasbv");System.out.println(treeSet);}
}

res:

[aaa, aaaaa, aasbv, bbbbb, badssd, xxxxxxxx]

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/340382.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

(超详细)4-YOLOV5改进-添加ShuffleAttention注意力机制

1、在yolov5/models下面新建一个SE.py文件&#xff0c;在里面放入下面的代码 代码如下&#xff1a; import numpy as np import torch from torch import nn from torch.nn import init from torch.nn.parameter import Parameterclass ShuffleAttention(nn.Module):def __…

第一个动态结构:链表

王有志&#xff0c;一个分享硬核Java技术的互金摸鱼侠加入Java人的提桶跑路群&#xff1a;共同富裕的Java人 今天我们一起学习线性表中的第二种数据结构&#xff1a;链表&#xff0c;也是真正意义上的第一个动态数据结构。今天的内容分为3个部分&#xff1a;认识链表&#xff0…

找不到msvcr120.dll怎样修复,分享4种修复方法

msvcr120.dll是Microsoft Visual C 2012 Redistributable Package的一个关键组件&#xff0c;负责提供C运行时库。许多应用程序在运行时都需要依赖这个库文件。然而&#xff0c;在日常使用过程中&#xff0c;不少用户会遇到msvcr120.dll丢失的问题&#xff0c;导致程序无法正常…

2024,AI Agent的密集爆发之年

最近这几天&#xff0c;相信已经有很多朋友看到了关于GPT Store、Vision Pro、Rabbit R1、AI pin、英伟达ACE&#xff08;Avatar Cloud Engine&#xff09;、钉钉个人助理、荣耀MagicOS 8.0等各类和AI技术深度结合的AI Agent或者承载AI Agent的平台。有些是和个人应用相关&…

Macos下修改Python版本

MacOS下修改Python版本 安装 查看本机已安装的Python版本&#xff1a;where python3 ~ where python3 /usr/bin/python3 /usr/local/bin/python3 /Library/Frameworks/Python.framework/Versions/3.12/bin/python3如果没有你想要的版本&#xff0c;去python官网下载安装包。…

软件安全测评需要关注哪些?湖南CMA、CNAS软件测试公司推荐

在当今信息化的社会&#xff0c;软件安全问题日益凸显&#xff0c;给个人和企业的数据安全造成了极大的威胁。为了保障软件的安全性&#xff0c;软件安全测评应运而生。 软件安全测评是通过对软件系统的评估&#xff0c;发现其中存在的安全漏洞和风险&#xff0c;为软件的开发…

数据结构栈、队列、链表、散列表

栈&#xff08;stack&#xff09; 栈&#xff08;stack&#xff09;是限制插入和删除只能在一个位置上进行的表&#xff0c;该位置是表的末端&#xff0c;叫做栈顶&#xff08;top&#xff09;。它是后进先出&#xff08;LIFO&#xff09;的。对栈的基本操作只有 push&#xf…

【PyQt小知识 - 7】:QLineEdit设置输入的文本以圆点或星号等方式显示

文章目录 setEchoMode setEchoMode 在PyQt中&#xff0c;QLineEdit是一种用于接收用户输入的小部件&#xff08;widget&#xff09;。setEchoMode是QLineEdit类中的一个方法&#xff0c;可以用于设置文本输入框中的文本显示模式。它接受一个参数来指定要使用的模式。 setEcho…

Docker启动报错:No chain/target/match by that name 处理

一、问题描述 某次OS升级重启后&#xff0c;发现docker redis实例无法启动&#xff0c;报错如下&#xff1a; Error response from daemon: driver failed programming external connectivity on endpoint vpm.redis.2 (f4b70fef65000bcacb574ee59e65d9b7a25f2abfa5dec0be9b74…

SpringBoot中使用SpringRetry实现重试机制(重试调用第三方API)

场景 SpringbootFastJson实现解析第三方http接口json数据为实体类(时间格式化转换、字段包含中文)&#xff1a; SpringbootFastJson实现解析第三方http接口json数据为实体类(时间格式化转换、字段包含中文)_fastjson 发送http请求 接收实体,出现日期转换异常-CSDN博客 在调用…

Fluids —— Whitewater (SOP)

目录 Whitewater Lifecycle Workflow Whitewater source Deformation sources Visualizing whitewater Whitewater solver Wind Foam erosion Repellants Whitewater postprocess 基于SOP的白水是对SOP FLIP工作流的增强&#xff1b;该系统与规模无关&#xff0c;无需…

XCTF:CatCatCat[WriteUP]

从题目中下载到一张图片和一个txt文件 编码的开头是&#xff1a;U2FsdGVkX1所以是rabbit加密 尝试使用密钥&#xff1a;91 密码不对&#xff0c;无法解密所以从图片下手 使用010Editor搜索图片文本内容 尝试搜索password、flag等敏感字体 直接拿到rabbit解密需要的密钥是&am…