当前位置:网站首页>Detailed explanation of set
Detailed explanation of set
2022-07-01 05:21:00 【Customer bank】
Catalog
One .Set aggregate
Set A collection is actually an interface ,HashSet and TreeSet Realized Set Interface , all Set Methods HashSet and TreeSet Also have .
characteristic :
- set Sets are unordered , Not repeated ( Disorder means not in the order in which we add to the set )
- Traverse through foreach, iterator , Cannot pass subscript , because set Set has no subscript
- The initial capacity is 16, Load factor 0.75 times , Expansion capacity increase 1 times
Two .HashSet aggregate
- HashSet It's the realization of Set Collection interface , therefore Set Set has , It also has .
- It only stores unique elements and allows null values . Storing unique elements means , If you add two 1, So there's one 1 be killed , Only 1 One 1 There is .
- from HashMap Support .
- The insertion order is not maintained
- Thread unsafe
foreach Loop traversal
If some elements are added, they will be covered , You can press and hold Ctrl Click on add Go in and see the source code . There is one in the source code boolean Methods , This method determines whether the newly added element already exists in the collection , If false Then there are already the same elements as this element , If true Then there is no such element , Add to the set .
notes : If you already have an element
package com.yjx.test; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.junit.Before; import org.junit.Test; public class Test01 { private Set<Integer> set=new HashSet<Integer>(); @Before public void list() { set.add(1); set.add(1); set.add(2); set.add(3); set.add(3); set.add(4); set.add(5); set.add(6); } @Test public void test01() { for(Integer e:set) { System.out.println(e); } } }set The method in the source code for adding a collection to determine whether an element exists in the collection
boolean add(E e);Get the results :
Iterator traverses the array
hasNext: Determine if there are any elements in the set
public void test02() { Iterator<Integer>it=set.iterator(); while(it.hasNext()) { System.out.println(it.next()); } }Get the results :
We create a student entity class , Then add the students to the set .
- Stundet Class must implement hashCode() and equals Method , Because they are used to compare whether two objects are equal and consistent
- You can try in stundet Class , And remove the difference between the two methods , If Studnet There is no such method in , So even if id Equal to name and age , It can still be added
Studnet class
package com.yjx.test; public class Stundet { private Integer id; private String name; private Integer age; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Stundet() { // TODO Auto-generated constructor stub } public Stundet(Integer id, String name, Integer age) { super(); this.id = id; this.name = name; this.age = age; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((age == null) ? 0 : age.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((name == null) ? 0 : name.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; Stundet other = (Stundet) obj; if (age == null) { if (other.age != null) return false; } else if (!age.equals(other.age)) return false; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } @Override public String toString() { return "Stundet [id=" + id + ", name=" + name + ", age=" + age + "]"; } }Method
Students like this id Same name as the student , But different ages , So they are not the same person , Both will be added .
public void test03() { // First create a collection Set<Stundet> set=new HashSet<Stundet>(); set.add(new Stundet(1," Zhang San ",18)); set.add(new Stundet(1," Zhang San ",19)); set.add(new Stundet(3," Zhang Wu ",16)); set.add(new Stundet(5," Zhang Liu ",11)); set.add(new Stundet(3," Zhang Qi ",12)); for(Stundet s:set) { System.out.println(s); } }Get the results :
But if we will be the first and the second will id And the name and age are set to the same , Then only one will be added .
public void test03() { // First create a collection Set<Stundet> set=new HashSet<Stundet>(); set.add(new Stundet(1," Zhang San ",18)); set.add(new Stundet(1," Zhang San ",18)); set.add(new Stundet(3," Zhang Wu ",16)); set.add(new Stundet(5," Zhang Liu ",11)); set.add(new Stundet(3," Zhang Qi ",12)); for(Stundet s:set) { System.out.println(s); } }Get the results : And it will help us according to id Make a sort
If we want to sort by age , This is where it comes in TreeSet, So let's look down .
3、 ... and .TreeSet aggregate
- Is a collection containing ordered elements without repetition
- The function is to provide orderly Set aggregate , Sort naturally or according to what is provided Comparator Sort
- TreeSet Is based on TreeMap Realized
What to use TreeSet aggregate ?
When we want to sort by what, we can use TreeSet aggregate , Here's how to use TreeSet Set to sort .
- The first method
We use Comparator Make a sort , You can grow up , You can also go from big to small , But there is a big problem with this method , If there are people of the same age , Then only one will stay , The others will not exist in the set .
This is sorted from small to large , Want from big to small , Just o2.getAge-o1.getAge.
public void test04() { TreeSet<Stundet> tree=new TreeSet<Stundet>(new Comparator<Stundet>() { @Override public int compare(Stundet o1, Stundet o2) { return o1.getAge() - o2.getAge(); } }); // First create a collection tree.add(new Stundet(1," Zhang San ",18)); tree.add(new Stundet(3," Zhang Wu ",16)); tree.add(new Stundet(5," Zhang Liu ",18)); tree.add(new Stundet(4," Zhang Qi ",12)); tree.add(new Stundet(6," Zhang Qi ",12)); for(Stundet s:tree) { System.out.println(s); } }Get the results :
We just said , Appear at the same age , Only one will be left , How to solve this problem , Look at the following code .
We added a judgment , When age is subtracted to 0, They are equal , Then according to their id Sort . This problem can be solved .
public void test04() { TreeSet<Stundet> tree=new TreeSet<Stundet>(new Comparator<Stundet>() { @Override public int compare(Stundet o1, Stundet o2) { if(o1.getAge() - o2.getAge()==0) { return o1.getId()-o2.getId(); } return o1.getAge() - o2.getAge(); } }); // First create a collection tree.add(new Stundet(1," Zhang San ",18)); tree.add(new Stundet(3," Zhang Wu ",16)); tree.add(new Stundet(5," Zhang Liu ",18)); tree.add(new Stundet(4," Zhang Qi ",12)); tree.add(new Stundet(6," Zhang Qi ",12)); for(Stundet s:tree) { System.out.println(s); } }Get the results : All the data exists ,id According to the order from small to large .
- The second method
We are Studnet Make judgments in entity classes , Realization Comparable
package com.yjx.test; import java.util.Comparator; public class Stundet implements Comparable<Stundet>{ private Integer id; private String name; private Integer age; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Stundet() { // TODO Auto-generated constructor stub } public Stundet(Integer id, String name, Integer age) { super(); this.id = id; this.name = name; this.age = age; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((age == null) ? 0 : age.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((name == null) ? 0 : name.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; Stundet other = (Stundet) obj; if (age == null) { if (other.age != null) return false; } else if (!age.equals(other.age)) return false; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } @Override public String toString() { return "Stundet [id=" + id + ", name=" + name + ", age=" + age + "]"; } @Override public int compareTo(Stundet o) { if(o.getAge()-this.getAge()==0) { return o.getId()-this.getId(); } return o.getAge()-this.getAge(); } }Test method code
@Test public void test05() { TreeSet<Stundet> tree=new TreeSet<Stundet>(); // First create a collection tree.add(new Stundet(1," Zhang San ",18)); tree.add(new Stundet(3," Zhang Wu ",16)); tree.add(new Stundet(5," Zhang Liu ",18)); tree.add(new Stundet(4," Zhang Qi ",12)); tree.add(new Stundet(6," Zhang Qi ",12)); for(Stundet s:tree) { System.out.println(s); } }This method is also possible , You'd better make a judgment , Avoid data of the same size and leave only one such case .
That's all for today's study .
边栏推荐
- Software intelligence: the "world" and "boundary" of AI sentient beings in AAAs system
- Unit testing with mongodb
- 如何选择导电滑环材料
- Global and Chinese markets of gps/gnss receiver modules 2022-2028: Research Report on technology, participants, trends, market size and share
- Vérification simple de la lecture et de l'écriture de qdatastream
- More than one file was found with OS independent path ‘lib/armeabi-v7a/libyuv.so‘.
- 3D建模与处理软件简介 刘利刚 中国科技大学
- Distributed transactions - Solutions
- LevelDB源码分析之LRU Cache
- Vmware workstation network card settings and three common network modes
猜你喜欢

CockroachDB 分布式事务源码分析之 TxnCoordSender

Intelligent operation and maintenance: visual management system based on BIM Technology

eBPF Cilium实战(2) - 底层网络可观测性

STM32 expansion board digital tube display

Leetcode1497- check whether array pairs can be divided by K - array - hash table - count
![Is there any good website or software for learning programming? [introduction to programming]?](/img/ae/68a5880f313c307880ac80bd200530.jpg)
Is there any good website or software for learning programming? [introduction to programming]?

Daily question -leetcode1175- permutation of prime numbers - Mathematics

在Rainbond中一键部署高可用 EMQX 集群

Numeric amount plus comma; JS two methods of adding three digits and a comma to numbers; JS data formatting

Summary of spanner's paper
随机推荐
Practice of combining rook CEPH and rainbow, a cloud native storage solution
QDataStream的簡單讀寫驗證
Tcp/ip explanation (version 2) notes / 3 link layer / 3.2 Ethernet and IEEE 802 lan/man standards
Use and principle of reentrantlock
HCIP Day13
【暑期每日一题】洛谷 P2637 第一次,第二次,成交!
Fluentd is easy to use. Combined with the rainbow plug-in market, log collection is faster
复制宝贝提示材质不能为空,如何解决?
Copier le matériel de conseils de bébé ne peut pas être vide, comment résoudre?
3D建模与处理软件简介 刘利刚 中国科技大学
el-form表单新增表单项动态校验;el-form校验动态表单v-if不生效;
Global and Chinese market of solder wire 2022-2028: Research Report on technology, participants, trends, market size and share
How to hide browser network IP address and modify IP internet access?
Use and principle of wait notify
Txncoordsender of cockroachdb distributed transaction source code analysis
Global and Chinese market of paper machine systems 2022-2028: Research Report on technology, participants, trends, market size and share
Pico neo3 handle grabs objects
Query long transaction
Rainbond结合NeuVector实践容器安全管理
LeetCode1497-检查数组对是否可以被 k 整除-数组-哈希表-计数




