Java SE
1.Set集合
Set用于存儲(chǔ)不重復(fù)的對(duì)象集合,在Set集合中存儲(chǔ)的對(duì)象中不存在兩個(gè)對(duì)象equals比較為true。
HashSet和TreeSet是Set集合兩個(gè)常用的實(shí)現(xiàn)類,分別用hash表和排序二叉樹的方式實(shí)現(xiàn)Set集合。
Set<Integer> set = new HashSet<Integer>();
Random r = new Random();
int i = 0;
while (set.size() < 20) {
set.add(r.nextInt()100);
i++;
}
System.out.println("i ="+i);
System.out.println(set);
Set集合的遍歷
Set集合不同于List集合,其中的元素不能喝書序的下標(biāo)對(duì)應(yīng),無法從set集合中取出特定的元素;如果希望遍歷Set集合中的元素只能調(diào)用其iterator方法,通過返回的Iterator對(duì)象來完成。
Set<String> strSet = new HashSet<String>();
strSet.add("One");strSet.add("Two");strSet.add("Three");
Iterator<String> it = strSet.iterator();
while (it.hasNext()){
String str = it.next();
System.out.println(str + "");
}
//Set集合的迭代輸出順序與其內(nèi)部的存儲(chǔ)結(jié)構(gòu)有關(guān)于元素的添加順序無關(guān).
HashSet和hashCode方法的關(guān)系
HashSet是Set接口的實(shí)現(xiàn)類,通過Hash表的方式實(shí)現(xiàn);
在將對(duì)象加入HashSet集合中時(shí),需要獲取對(duì)象的hashCode值通過Hsh算法索引到對(duì)象的存儲(chǔ)空間。
hashCode方法
對(duì)于重寫了equals方法的對(duì)象,一般要妥善的重寫繼承自O(shè)bject類的hashCode方法。
2.Map集合
Map接口定義的集合又稱為查找表,用于存儲(chǔ)“Key-Value"映射對(duì)。
根據(jù)內(nèi)部數(shù)據(jù)結(jié)構(gòu)的不同,Map接口有多種實(shí)現(xiàn)類,其中常用的有內(nèi)部hash表實(shí)現(xiàn)的HashMap和內(nèi)部為排序二叉樹實(shí)現(xiàn)的TreeMap。Map接口常用的方法為get和put。
String line = "169,589,798,723,589,169,169,723";
String[] arr = line.split(line);
Map<String,Integer> map = new HashMap<String, Integer>();
for (int i = 0; i < arr.length; i++) {
if (map.containsKey(arr[i])){
map.put(arr[i],map.get(arr[i]+1));
}else {
map.put(arr[i],1);
}
}
System.out.println(map);//{723=2,798=1,169=3,589=2}
HashMap性能優(yōu)化
Capacity:容量,Hash里面bucket的數(shù)量,也是三列數(shù)組大小。
Initial capacity:初始容量,默認(rèn)構(gòu)建容量16,也可以使用特定容量。
Size:大小,當(dāng)前散列表中存儲(chǔ)數(shù)據(jù)的數(shù)量。
Load factor:加載因子,默認(rèn)為0.75,當(dāng)前散列表增加數(shù)據(jù)如果size、capacity的值大于load factor則發(fā)生擴(kuò)充并重新散列。
注:加載因子較小時(shí)候散列查找性能會(huì)提高,同時(shí)也浪費(fèi)了散列桶空間容量。0.75是性能和控件相對(duì)平衡結(jié)合。