当前位置:网站首页>你不知道的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);
}
}
运行输出结果:
边栏推荐
- Base64 编码原来还可以这么理解
- GeoServer offline map service construction and layer Publishing
- It's no exaggeration to say that this is the most user-friendly basic tutorial of pytest I've ever seen
- 可视化搭建页面工具的前世今生
- AtCoder Beginner Contest 254
- Socket and socket address
- mathjax 入门(web显示数学公式,矢量的)
- TiDB混合部署拓扑
- TiDB数据迁移场景综述
- Add vector formula in rich text editor (MathType for TinyMCE, visual addition)
猜你喜欢
[email protected] : The platform “win32“ is incompatible with this module."/>
info [email protected] : The platform “win32“ is incompatible with this module.
Solve the problem that El radio group cannot be edited after echo
Implement a server with multi process concurrency
CTO如何帮助业务?
[noi Simulation Competition] scraping (dynamic planning)
Why can't programmers who can only program become excellent developers?
Kityformula editor configure font size and spacing
MathML to latex
kityformula-editor 配置字号和间距
Reuse and distribution
随机推荐
Li Chuang EDA learning notes 15: draw border or import border (DXF file)
Base64 coding can be understood this way
TiDB 环境与系统配置检查
广州市应急管理局发布7月高温高湿化工安全提醒
MFC CString to char*
Implementation of n queen in C language
如何用 Sysbench 测试 TiDB
Large top heap, small top heap and heap sequencing
[noi simulation] Elis (greedy, simulation)
Yolov6 training: various problems encountered in training your dataset
【题解】Educational Codeforces Round 82
可视化搭建页面工具的前世今生
为什么只会编程的程序员无法成为优秀的开发者?
How does CTO help the business?
forEach的错误用法,你都学废了吗
IE 浏览器正式退休
C language exercises - (array)
LeetCode_字符串_简单_412.Fizz Buzz
CDN 在游戏领域的应用
表格响应式布局小技巧