当前位置:网站首页>你不知道的Set集合
你不知道的Set集合
2022-07-02 12:00:00 【小阿飞_】
本期精彩:
Set接口
基本介绍
特点:
- Set:无序(存入和取出的循序不同故不能使用下标遍历),不重复
- List:有序,元素不可重复
遍历:foreach,迭代器
扩容: 初始容量16,负载因子0.75,扩容增量1倍
Set、Queue、List都实现Collection,而Map则不实现Collection接口

ThreeSet与Collection等关系的UML图

看不明白这个图中的关系箭头的可以去看一下这篇博客,里面详细介绍了UML图
List集合&UML图_小阿飞_的博客-CSDN博客UML图一看就懂的秘诀 and List接口中的集合你了解多少?https://blog.csdn.net/yifei_345678/article/details/125483171?spm=1001.2014.3001.5501
Set接口的实现类
Set和List集合一样属于接口,无法直接创建实例化对象,需要实现类来创建,HashSet、ThreeSet都是常用的实现类
1、HashSet
特点
- 非线程安全
- 由HashMap支持
- 不保证插入顺序
- 存在于java.util包中的类,同时也被称为集合,该容器中只能存储不重复的对象
- 它存储唯一元素并允许空值(依据对象的hashcode来确定该元素是否存在)
- 性能参数:初始容量,负载因子(默认值: 初始容量16,负载因子0.75)
HashSet的实现
对于 HashSet 而言,它是基于 HashMap 实现的,HashSet 底层使用 HashMap 来保存所有元素,因此 HashSet 的实现比较简单,相关 HashSet 的操作,基本上都是直接调用底层 HashMap 的相关方法来完成,我们应该为保存到 HashSet 中的对象覆盖 hashCode() 和 equals()
已知实现接口有:
Serializable, Cloneable, Iterable<E>, Collection<E>, Set<E>
已知子类:
JobStateReasons, LinkedHashSet
代码知识
曾经有一道题,问如何把ArrayList中重复的元素去掉(去重),方法有很多,小猿们可以自己试着写几个,这里提供一个比较简单快速的方法:使用HashSet去重
public class SetDemo {
private List<Integer> list = new ArrayList<>();
@BeforeAll
public void setup() {
set.add(1);
set.add(1);
set.add(2);
set.add(2);
set.add(3);
set.add(3);
}
@Test
public void test01() {
List<Integer> tmp = new ArrayList<>(new HashSet<Integer>(list));
System.out.println(tmp);
}
}输出结果是123(ArrayList是可以存放重复元素的,但是这里使用了HashSet去重)
1、新建一个Set集合并放入元素
public class SetDemo {
private Set<Integer> set = new HashSet<>();
@BeforeAll
public void setup() {
set.add(1);
set.add(1);
set.add(2);
set.add(4);
set.add(5);
set.add(3);
}
}2、可以使用下面两种方法遍历其中的元素,由于HashSet中只能存储不重复的对象,所以输出时会自动把重复的元素去重
@Test
public void test02() {
for(Integer e: set) {
System.out.println(e);
}
}
//使用迭代器
@Test
public void test03() {
Iterator<Integer> it = set.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
} 3、set.remove(i)中传入的是元素,这是由于HashSet不保证插入顺序,没有下标概念,所以只能传入元素
@Test
public void test05() {
set.remove(3);
System.out.println(set);
}删除的是第一步里面Set集合里面的元素3,输出的是1245
2、TreeSet
特点
- 是一个包含有序的且没有重复元素的集合
- 作用是提供有序的Set集合,自然排序(比如123456...)或者根据提供的Comparator(比较器)进行排序
- TreeSet是基于TreeMap实现的,而ThreeMap的底层是Map(键值对)
代码知识
创建一个学生类并实现编比较器接口
public class Student implements Comparable<Student>{
private Integer sid;
private String sname;
private int age;
public Student(Integer sid, String sname, int age) {
super();
this.sid = sid;
this.sname = sname;
this.age = age;
}
public Integer getSid() {
return sid;
}
public void setSid(Integer sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}还需要在这个学生类中实现hashCode和equals方法:
/*
*hashCode可以将学号名字努力转成唯一的数字,相对于身份证
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((sid == null) ? 0 : sid.hashCode());
result = prime * result + ((sname == null) ? 0 : sname.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (age != other.age)
return false;
if (sid == null) {
if (other.sid != null)
return false;
} else if (!sid.equals(other.sid))
return false;
if (sname == null) {
if (other.sname != null)
return false;
} else if (!sname.equals(other.sname))
return false;
return true;//学号名字年龄都相等才是同一个学生
}
@Override
public String toString() {
return "Student [sid=" + sid + ", sname=" + sname + ", age=" + age + "]";
}
/**
* 实现Comparable<Student>接口后需要重写的方法
* 根据年龄排序,年龄相同则比较学号,默认是升序
*/
@Override
public int compareTo(Student o) {
if(this.getAge()-o.getAge()==0) {
return this.getSid()-o.getSid();
}
return this.getAge() - o.getAge();
}然后再使用ThreeSet
@Test
public void test04() {
TreeSet<Student> stu = new TreeSet<>();
stu.add(new Student(1,"zs", 18));
stu.add(new Student(1,"zs", 18));
stu.add(new Student(2,"ls", 19));
stu.add(new Student(4,"lihao", 10));
stu.add(new Student(7,"lihao", 18));
stu.add(new Student(5,"zengfanyan", 20));
stu.add(new Student(3,"we", 30));
for(Student s: stu) {
System.out.println(s);
}
} 运行输出结果:

边栏推荐
- 学习使用php实现公历农历转换的方法代码
- How does CTO help the business?
- 蜻蜓低代码安全工具平台开发之路
- Tidb environment and system configuration check
- 08_ 串
- TiDB跨数据中心部署拓扑
- taobao. logistics. dummy. Send (no logistics delivery processing) interface, Taobao store delivery API interface, Taobao order delivery interface, Taobao R2 interface, Taobao oau2.0 interface
- 使用 TiUP 部署 TiDB 集群
- 可视化搭建页面工具的前世今生
- LeetCode 2320. Count the number of ways to place the house
猜你喜欢

06_栈和队列转换

使用mathtype编辑公式,复制粘贴时设置成仅包含mathjax语法的公式

C#代码审计实战+前置知识

可视化搭建页面工具的前世今生

Table responsive layout tips

kityformula-editor 配置字号和间距
![[noi Simulation Competition] scraping (dynamic planning)](/img/ee/27a07f80207a2925f5065e633eb39f.png)
[noi Simulation Competition] scraping (dynamic planning)

Error: NPM warn config global ` --global`, `--local` are deprecated Use `--location=global` instead.
![[Space & single cellomics] phase 1: single cell binding space transcriptome research PDAC tumor microenvironment](/img/e1/c8e81570ab78de1e488a611c25ebb9.png)
[Space & single cellomics] phase 1: single cell binding space transcriptome research PDAC tumor microenvironment

Advanced C language (learn malloc & calloc & realloc & free in simple dynamic memory management)
随机推荐
Kityformula editor configure font size and spacing
MFC timer usage
vChain: Enabling Verifiable Boolean Range Queries over Blockchain Databases(sigmod‘2019)
MFC CString to char*
Database connection pool and data source
taobao. trade. memo. Add (add remarks to a transaction) interface, Taobao store flag insertion interface, Taobao order flag insertion API interface, oauth2.0 interface
如何对 TiDB 进行 TPC-C 测试
Slashgear shares 2021 life changing technology products, which are somewhat unexpected
CodeCraft-22 and Codeforces Round #795 (Div. 2)D,E
Socket and socket address
LeetCode 209. 长度最小的子数组
07_哈希
Huawei interview question: no palindrome string
Some Chinese character codes in the user privacy agreement are not standardized, which leads to the display of garbled codes on the web page. It needs to be found and handled uniformly
Record an error report, solve the experience, rely on repetition
用户隐私协议有些汉字编码不规范导致网页显示乱码,需要统一找出来处理一下
LeetCode - 搜索二维矩阵
[untitled] leetcode 2321 Maximum score of concatenated array
C thread transfer parameters
【题解】Educational Codeforces Round 82