当前位置:网站首页>Set set you don't know
Set set you don't know
2022-07-02 15:13:00 【Xiao afai_】
This issue is wonderful :
Set Implementation class of interface
HashSet The implementation of the
Set Interface
Basic introduction
characteristic :
- Set: disorder ( The sequence of deposit and withdrawal is different, so the subscript cannot be used to traverse ), No repetition
- List: Orderly , Element is not repeatable
Traverse :foreach, iterator
Capacity expansion : Initial capacity 16, Load factor 0.75, Expansion increment 1 times
Set、Queue、List implement Collection, and Map Will not be achieved Collection Interface

ThreeSet And Collection etc. Relational UML chart

Those who can't understand the relationship arrow in this figure can go to this blog , It's introduced in detail UML chart
List aggregate &UML chart _ Little Alfie _ The blog of -CSDN Blog UML The secret that you can understand at a glance and List How much do you know about the set in the interface ?https://blog.csdn.net/yifei_345678/article/details/125483171?spm=1001.2014.3001.5501
Set Implementation class of interface
Set and List Collections also belong to interfaces , Cannot directly create an instantiated object , You need to implement classes to create ,HashSet、ThreeSet Are commonly used implementation classes
1、HashSet
characteristic
- Non-thread safety
- from HashMap Support
- There is no guarantee of insertion order
- Exist in java.util package Class in , It is also called a set , In this container Only non repeating objects can be stored
- It stores The only element And allow null values ( According to the hashcode To determine whether the element exists )
- performance parameter : Initial capacity , Load factor ( The default value is : Initial capacity 16, Load factor 0.75)
HashSet The implementation of the
about HashSet for , It is based on HashMap Realized ,HashSet Bottom use HashMap To save all elements , therefore HashSet The implementation of is relatively simple , relevant HashSet The operation of , Basically, they call the underlying layer directly HashMap To complete , We should be Save to for HashSet Object overlay in hashCode() and equals()
Known implementation interfaces are :
Serializable, Cloneable, Iterable<E>, Collection<E>, Set<E>
Known subclasses :
JobStateReasons, LinkedHashSet
Code knowledge
Once there was a problem , Ask how to ArrayList Remove the repeated elements in ( duplicate removal ), There are many ways , Little apes can try to write a few by themselves , Here is a simple and fast method : Use HashSet duplicate removal
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);
}
}The output is 123(ArrayList It can store repeated elements , But here we use HashSet duplicate removal )
1、 Create a new one Set Set and put elements
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、 You can use the following two methods to traverse the elements , because HashSet Only non duplicate objects can be stored in , Therefore, the repeated elements will be automatically de duplicated when outputting
@Test
public void test02() {
for(Integer e: set) {
System.out.println(e);
}
}
// Using Iterators
@Test
public void test03() {
Iterator<Integer> it = set.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
} 3、set.remove(i) What is passed in is the element , This is because HashSet There is no guarantee of insertion order , No subscript concept , So you can only pass in elements
@Test
public void test05() {
set.remove(3);
System.out.println(set);
}Delete the first step Set The elements in the collection 3, The output is 1245
2、TreeSet
characteristic
- Is a containing Orderly And There are no repeating elements Set
- Role is Provide orderly Set aggregate , Natural ordering ( such as 123456...) Or according to the information provided Comparator( The comparator ) Sort
- TreeSet Is based on TreeMap Realized , and ThreeMap The bottom is Map( Key value pair )
Code knowledge
Create a student class and implement the comparator interface
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;
}
}It also needs to be implemented in this student class hashCode and equals Method :
/*
*hashCode You can try to turn the student name into a unique number , Compared with ID card
*/
@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;// Students with the same student number, name and age are the same students
}
@Override
public String toString() {
return "Student [sid=" + sid + ", sname=" + sname + ", age=" + age + "]";
}
/**
* Realization Comparable<Student> Methods that need to be rewritten after the interface
* Sort by age , The same age is compared with the student number , The default is ascending
*/
@Override
public int compareTo(Student o) {
if(this.getAge()-o.getAge()==0) {
return this.getSid()-o.getSid();
}
return this.getAge() - o.getAge();
}And then use 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);
}
} Run output :

边栏推荐
猜你喜欢
随机推荐
使用 TiUP 部署 TiDB 集群
[noi simulation] Elis (greedy, simulation)
用户隐私协议有些汉字编码不规范导致网页显示乱码,需要统一找出来处理一下
c语言入门--数组
About text selection in web pages and counting the length of selected text
哈夫曼树:(1)输入各字符及其权值(2)构造哈夫曼树(3)进行哈夫曼编码(4)查找HC[i],得到各字符的哈夫曼编码
C# 线程传参
Have you learned the wrong usage of foreach
C # delay, start the timer in the thread, and obtain the system time
LeetCode 2320. 统计放置房子的方式数
Implementation of n queen in C language
Slashgear shares 2021 life changing technology products, which are somewhat unexpected
二叉树的遍历方式主要有:先序遍历、中序遍历、后序遍历、层次遍历。先序、中序、后序其实指的是父节点被访问的次序。若在遍历过程中,父节点先于它的子节点被访问,就是先序遍历;
TiDB数据迁移工具概览
蜻蜓低代码安全工具平台开发之路
Huawei interview question: no palindrome string
XML配置文件
Socket and socket address
MFC timer usage
你不知道的Set集合








![[C language] explain the initial and advanced levels of the pointer and points for attention (1)](/img/61/1619bd2e959bae1b769963f66bab4e.png)
