当前位置:网站首页>Set set detailed explanation
Set set detailed explanation
2022-07-01 05:20:00 【Les clients.】
Table des matières
L'Itérateur traverse le tableau
Un..SetEnsemble
SetLa collection est en fait une interface,HashSetEtTreeSetC'est fait.SetInterface,Tous lesSetLes méthodes disponiblesHashSetEtTreeSetIl y en a aussi.
Caractéristiques:
- setLes collections sont désordonnées,Non répétitif(Le désordre signifie qu'il ne suit pas l'ordre dans lequel nous ajoutons à l'ensemble)
- Traverséeforeach,Itérateur,Impossible de passer l'indice,Parce quesetLa collection n'a pas d'indice
- Capacité initiale16,Facteur de charge0.75X,Augmentation de la capacité1X
2..HashSetEnsemble
- HashSetEst la réalisationSetInterface de collecte,Alors...Set Ce que la collection a , Il a aussi .
- Il ne stocke que des éléments uniques et permet des valeurs nulles . Stocker un élément unique signifie , Si vous en Ajoutez deux 1,Il y en a un.1Il va se faire tuer,Seulement1Un1Existe.
- ParHashMapSoutien.
- Ne pas maintenir l'ordre d'insertion
- Thread Unsafe
foreachItération circulaire
S'il y a des éléments dedans, ils seront écrasés. , Tout le monde peut tenir CtrlCliquez suradd Allez voir le code source .Il y a unbooleanMéthode, La méthode consiste à déterminer si l'élément nouvellement ajouté existe déjà dans la collection. ,Si ouifalse Il y a déjà le même élément à l'intérieur. ,Si ouitrue Alors il n'y a pas d'élément , Ajouter à la collection .
Note:: Si un élément existe déjà
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 Méthode de détermination de l'existence d'éléments dans une collection dans le code source ajouté à la collection
boolean add(E e);
Obtenir des résultats:
L'Itérateur traverse le tableau
hasNext:Déterminer s'il reste des éléments dans la collection
public void test02() { Iterator<Integer>it=set.iterator(); while(it.hasNext()) { System.out.println(it.next()); } }
Obtenir des résultats:
Nous créons une classe d'entité étudiante , Puis ajoutez les élèves à la collection .
- Stundet La classe doit implémenter hashCode()EtequalsMéthodes, Parce qu'ils comparent deux objets égaux et cohérents
- Tout le monde peut essayer dans stundet Implémenter les deux méthodes dans la classe , La différence entre les deux méthodes ,SiStudnetIl n'y a pas de méthode,Alors, même siid Et le même nom et l'âge. , Peut encore être ajouté
StudnetCatégorie
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 + "]"; } }
Méthodes
Des étudiants comme ça id Même nom que l'étudiant , Mais l'âge est différent , Donc ce ne sont pas les mêmes personnes , Les deux seront ajoutés. .
public void test03() { //Commencez par créer une 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,"Chang - Siu.",11)); set.add(new Stundet(3,"Zhang Qi",12)); for(Stundet s:set) { System.out.println(s); } }
Obtenir des résultats:
Mais si nous prenons le premier et le second, id Avec le même nom et l'âge , Un seul sera ajouté. .
public void test03() { //Commencez par créer une 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,"Chang - Siu.",11)); set.add(new Stundet(3,"Zhang Qi",12)); for(Stundet s:set) { System.out.println(s); } }
Obtenir des résultats: Et ça nous aidera à nous baser sur idFaire un tri
Si nous voulons utiliser un classement par âge ,C'est le moment.TreeSet,Regarde en bas..
Trois.TreeSetEnsemble
- Est une collection ordonnée sans éléments répétitifs
- La fonction est de fournir l'ordre SetEnsemble, Trier naturellement ou selon ce qui est fourni ComparatorTrier
- TreeSetEst basé surTreeMapRéalisé
Qu'est - ce queTreeSetEnsemble?
On peut l'utiliser quand on veut trier quelque chose. TreeSetEnsemble,Voici comment utiliserTreeSetTrier les collections.
- La première approche
Nous utilisonsComparatorFaire un tri, Peut être de petite à grande , Peut également être de grande à petite , Mais cette approche pose un gros problème. , Si vous avez le même âge , Il n'en restera qu'un , Les autres n'existent pas dans la collection. .
Ceci est trié de petit à grand , Je veux passer du grand au petit ,Justeo2.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(); } }); //Commencez par créer une collection tree.add(new Stundet(1,"Zhang San",18)); tree.add(new Stundet(3,"Zhang Wu",16)); tree.add(new Stundet(5,"Chang - Siu.",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); } }
Obtenir des résultats:
On vient de dire , Le même âge apparaît , Il ne restera qu'un , Comment résoudre ce problème? , Regardez le code ci - dessous .
Nous avons ajouté un jugement , Quand l'âge est réduit à 0, Ils sont égaux , Alors, selon leur idTrier. Ça résoudra ce problème. .
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(); } }); //Commencez par créer une collection tree.add(new Stundet(1,"Zhang San",18)); tree.add(new Stundet(3,"Zhang Wu",16)); tree.add(new Stundet(5,"Chang - Siu.",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); } }
Obtenir des résultats:Toutes les données existent,id Dans l'ordre décroissant .
- Deuxième approche
On est là.Studnet Faire des jugements dans les classes d'entités ,RéalisationComparable
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(); } }
Code de la méthode d'essai
@Test public void test05() { TreeSet<Stundet> tree=new TreeSet<Stundet>(); //Commencez par créer une collection tree.add(new Stundet(1,"Zhang San",18)); tree.add(new Stundet(3,"Zhang Wu",16)); tree.add(new Stundet(5,"Chang - Siu.",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); } }
C'est une bonne idée. , Vous feriez mieux de faire un jugement , Évitez d'avoir des données de la même taille et laissez - en une seule. .
C'est ici que nous allons étudier aujourd'hui..
边栏推荐
- AcWing 885. Find the combination number I (recursive preprocessing)
- Things generated by busybox
- [daily question in summer] letter delivery by p1629 postman in Luogu (to be continued...)
- Spanner 论文小结
- Introduction of 3D Modeling and Processing Software Liu Ligang, Chinese University of Science and Technology
- Global and Chinese market of search engine optimization (SEO) software 2022-2028: Research Report on technology, participants, trends, market size and share
- 【暑期每日一题】洛谷 P2026 求一次函数解析式
- Actual combat: gateway api-2022.2.13
- Global and Chinese market of paper machine systems 2022-2028: Research Report on technology, participants, trends, market size and share
- Global and Chinese market for kitchen range hoods 2022-2028: Research Report on technology, participants, trends, market size and share
猜你喜欢
Solution: drag the Xib control to the code file, and an error setvalue:forundefined key:this class is not key value coding compliant for the key is reported
[RootersCTF2019]babyWeb
eBPF Cilium实战(2) - 底层网络可观测性
Actual combat: gateway api-2022.2.13
Ebpf cilium practice (2) - underlying network observability
Copier le matériel de conseils de bébé ne peut pas être vide, comment résoudre?
Spanner 论文小结
Is there any good website or software for learning programming? [introduction to programming]?
0xc000007b应用程序无法正常启动解决方案(亲测有效)
LeetCode1497-检查数组对是否可以被 k 整除-数组-哈希表-计数
随机推荐
AcWing 887. Finding combinatorial number III (Lucas theorem)
Use and principle of reentrantlock
Implementation of distributed lock
Precautions for use of conductive slip ring
How to hide browser network IP address and modify IP internet access?
Global and Chinese markets for business weather forecasting 2022-2028: Research Report on technology, participants, trends, market size and share
Software intelligence: the "world" and "boundary" of AI sentient beings in AAAs system
One click deployment of highly available emqx clusters in rainbow
Is there any good website or software for learning programming? [introduction to programming]?
Use of STM32 expansion board temperature sensor and temperature humidity sensor
HCIP Day13
Global and Chinese market of digital badge 2022-2028: Research Report on technology, participants, trends, market size and share
Global and Chinese market of 3D CAD 2022-2028: Research Report on technology, participants, trends, market size and share
数字金额加逗号;js给数字加三位一逗号间隔的两种方法;js数据格式化
Introduction to 3D modeling and processing software Liu Ligang University of science and technology of China
AcWing 885. Find the combination number I (recursive preprocessing)
Use and principle of AQS related implementation classes
轻松上手Fluentd,结合 Rainbond 插件市场,日志收集更快捷
Distributed - summary list
El cascade echo failed; El cascader does not echo