当前位置:网站首页>Set集合詳細講解
Set集合詳細講解
2022-07-01 05:19:00 【客行.】
目錄
一.Set集合
Set集合其實就是一個接口,HashSet和TreeSet實現了Set接口,所有Set所具備的方法HashSet和TreeSet也是具備的。
特點:
- set集合是無序的,不重複的(無序的意思是不會按照我們增加進集合的順序)
- 遍曆通過foreach,迭代器,無法通過下標,因為set集合沒有下標
- 初始容量為16,負載因子0.75倍,擴容量增加1倍
二.HashSet集合
- HashSet是實現Set集合接口的,所以Set集合所具備的,它也具備。
- 它只儲存唯一元素並且允許為空值。儲存唯一元素的意思是,如果你增加兩個1,那麼有一個1會被幹掉,只有1一個1存在。
- 由HashMap支持。
- 不保持插入順序
- 線程不安全
foreach循環遍曆
如果裏面有的元素增加進去會被覆蓋,大家可以按住Ctrl點擊add進去看源碼。源碼裏有一個boolean的方法,該方法是判斷新增加的元素在該集合是否已經存在了,如果為false那麼裏面已經存在和該元素一樣的元素,如果為true那麼裏面沒有該元素,增加進該集合。
注:如果已經有元素存在
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集合增加的源碼裏的判斷元素是否在集合中存在的方法
boolean add(E e);得到結果:
迭代器遍曆數組
hasNext:判斷集合中是否還有元素
public void test02() { Iterator<Integer>it=set.iterator(); while(it.hasNext()) { System.out.println(it.next()); } }得到結果:
我們創建一個學生實體類,然後將學生增加進集合。
- Stundet類一定要實現hashCode()和equals方法,因為他們用來對比兩個對象是否相等一致
- 大家可以試一下在stundet類中實現這兩個方法,和去除這兩個方法的區別,如果Studnet中沒有這個方法,那麼就算id和名字和年齡全相等,依舊可以增加進去
Studnet類
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 + "]"; } }方法
像這種學生id和學生名字都相同,但是年齡不同,所以他們不是同一個人,兩個都會增加進去的。
public void test03() { //先創建一個集合 Set<Stundet> set=new HashSet<Stundet>(); set.add(new Stundet(1,"張三",18)); set.add(new Stundet(1,"張三",19)); set.add(new Stundet(3,"張五",16)); set.add(new Stundet(5,"張六",11)); set.add(new Stundet(3,"張七",12)); for(Stundet s:set) { System.out.println(s); } }得到結果:
但是如果我們將第一個和第二個將id和名字和年齡都設置為一樣的,那麼只有一個會增加進去。
public void test03() { //先創建一個集合 Set<Stundet> set=new HashSet<Stundet>(); set.add(new Stundet(1,"張三",18)); set.add(new Stundet(1,"張三",18)); set.add(new Stundet(3,"張五",16)); set.add(new Stundet(5,"張六",11)); set.add(new Stundet(3,"張七",12)); for(Stundet s:set) { System.out.println(s); } }得到結果:而且還會幫我們根據id進行一個排序
如果我們想用根據年齡進行一個排序,這個時候就要用到TreeSet,接著往下看。
三.TreeSet集合
- 是一個包含有序的且沒有重複元素的集合
- 作用是提供有序的Set集合,自然排序或者根據提供的Comparator進行排序
- TreeSet是基於TreeMap實現的
什麼使用TreeSet集合?
當我們想根據什麼進行排序的話就可以使用TreeSet集合,下面就教大家如何使用TreeSet集合進行排序。
- 第一種方法
我們使用Comparator進行一個排序,可以從小到大,也可以從大到小,但是這種方法存在一個很大的問題,如果有年齡相同的,那麼只會有一個留下,其他的就會不存在該集合中了。
這個是從小到大排序的,想要從大到小,就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(); } }); //先創建一個集合 tree.add(new Stundet(1,"張三",18)); tree.add(new Stundet(3,"張五",16)); tree.add(new Stundet(5,"張六",18)); tree.add(new Stundet(4,"張七",12)); tree.add(new Stundet(6,"張七",12)); for(Stundet s:tree) { System.out.println(s); } }得到結果:
剛剛我們也說了,出現年齡相同,只會留下一個,那麼這種方法該如何解决嘞,大家看下面代碼。
我們增加了一個判斷,當年齡相减為0,他們相等,那就根據他們的id進行排序。就可以解决這樣子的問題啦。
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(); } }); //先創建一個集合 tree.add(new Stundet(1,"張三",18)); tree.add(new Stundet(3,"張五",16)); tree.add(new Stundet(5,"張六",18)); tree.add(new Stundet(4,"張七",12)); tree.add(new Stundet(6,"張七",12)); for(Stundet s:tree) { System.out.println(s); } }得到結果:所有的數據都存在,id根據從小到大的順序。
- 第二種方法
我們在Studnet實體類中做判斷,實現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 public void test05() { TreeSet<Stundet> tree=new TreeSet<Stundet>(); //先創建一個集合 tree.add(new Stundet(1,"張三",18)); tree.add(new Stundet(3,"張五",16)); tree.add(new Stundet(5,"張六",18)); tree.add(new Stundet(4,"張七",12)); tree.add(new Stundet(6,"張七",12)); for(Stundet s:tree) { System.out.println(s); } }這種方法也是可以的噢,大家最好做個判斷,避免出現一樣大的數據而只留下一個這種情况。
今天的學習就到這裏啦。
边栏推荐
- 3D建模与处理软件简介 刘利刚 中国科技大学
- Copier le matériel de conseils de bébé ne peut pas être vide, comment résoudre?
- Distributed transactions - Solutions
- LeetCode1497-检查数组对是否可以被 k 整除-数组-哈希表-计数
- tar命令
- Fluentd is easy to use. Combined with the rainbow plug-in market, log collection is faster
- Global and Chinese market of search engine optimization (SEO) software 2022-2028: Research Report on technology, participants, trends, market size and share
- LeetCode522-最长特殊序列II-哈希表-字符串-双指针
- 数字金额加逗号;js给数字加三位一逗号间隔的两种方法;js数据格式化
- CockroachDB 分布式事务源码分析之 TxnCoordSender
猜你喜欢

Txncoordsender of cockroachdb distributed transaction source code analysis

导电滑环短路的原因以及应对措施

0xc000007b应用程序无法正常启动解决方案(亲测有效)

Dynamic verification of new form items in El form; El form verifies that the dynamic form V-IF does not take effect;

How to traverse massive data in redis

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

Causes of short circuit of conductive slip ring and Countermeasures

使用 Nocalhost 开发 Rainbond 上的微服务应用

Lock free concurrency of JUC (leguan lock)

Rainbond结合NeuVector实践容器安全管理
随机推荐
Global and Chinese market of mainboard 2022-2028: Research Report on technology, participants, trends, market size and share
[Yugong series] February 2022 Net architecture class 005 ABP vNext Net core web application getting started configuration
使用 Nocalhost 开发 Rainbond 上的微服务应用
Lock free concurrency of JUC (leguan lock)
FileOutPutStream
Leetcode316- remove duplicate letters - stack - greedy - string
More than one file was found with OS independent path ‘lib/armeabi-v7a/libyuv. so‘.
Pico neo3 handle grabs objects
AcWing 886. Finding combinatorial number II (pretreatment factorial)
智慧运维:基于 BIM 技术的可视化管理系统
Global and Chinese market of solder wire 2022-2028: Research Report on technology, participants, trends, market size and share
1076 Forwards on Weibo
Global and Chinese markets of superconductor 2022-2028: Research Report on technology, participants, trends, market size and share
STM32 expansion board digital tube display
CockroachDB 分布式事务源码分析之 TxnCoordSender
Global and Chinese market of paper machine systems 2022-2028: Research Report on technology, participants, trends, market size and share
Vmware workstation network card settings and three common network modes
Flutter can refresh data every time the interface comes in
Variable binding and deconstruction for rudimentary rust
Serialization and deserialization of objects




