当前位置:网站首页>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..
边栏推荐
- Daily question -leetcode1175- permutation of prime numbers - Mathematics
- 导电滑环短路的原因以及应对措施
- 0xc000007b the application cannot start the solution normally (the pro test is valid)
- Precautions for use of conductive slip ring
- [daily question in summer] function of rogu p3742 UMI
- Serialization and deserialization of objects
- Practice of combining rook CEPH and rainbow, a cloud native storage solution
- 积分商城游戏能够给商家带来什么?怎么搭建积分商城?
- Data consistency between redis and database
- Oracle views the creation time of the tablespace in the database
猜你喜欢

Leetcode522- longest special sequence ii- hash table - String - double pointer

How to hide browser network IP address and modify IP internet access?

Application and principle of ThreadPoolExecutor thread pool

Txncoordsender of cockroachdb distributed transaction source code analysis

Summary of spanner's paper

Single page application

How to meet the requirements of source code confidentiality and source code security management

Actual combat: gateway api-2022.2.13

STM32 expansion board digital tube display

LevelDB源码分析之memtable
随机推荐
Unit testing with mongodb
Use and principle of wait notify
Leetcode1497- check whether array pairs can be divided by K - array - hash table - count
Principle, technology and implementation scheme of data consistency in distributed database
Copy baby prompt: material cannot be empty. How to solve it?
【暑期每日一题】洛谷 P2026 求一次函数解析式
HCIP Day13
数字金额加逗号;js给数字加三位一逗号间隔的两种方法;js数据格式化
tar命令
Causes of short circuit of conductive slip ring and Countermeasures
0xc000007b应用程序无法正常启动解决方案(亲测有效)
Worried about infringement? Must share copyrightless materials on the website. Don't worry about the lack of materials for video clips
One click deployment of highly available emqx clusters in rainbow
Global and Chinese market of search engine optimization (SEO) software 2022-2028: Research Report on technology, participants, trends, market size and share
How to traverse massive data in redis
工业导电滑环的应用
Dynamic verification of new form items in El form; El form verifies that the dynamic form V-IF does not take effect;
复制宝贝提示材质不能为空,如何解决?
[une question par jour pendant l'été] course luogu p1568
Character input stream and character output stream




