09Set接口的特點
A:Set接口的特點
a:它是個不包含重復(fù)元素的集合猛频。
b:Set集合取出元素的方式可以采用:迭代器刊咳、增強(qiáng)for辕万。
c:Set集合有多個子類枢步,這里我們介紹其中的HashSet沉删、LinkedHashSet這兩個集合。
10Set集合存儲和迭代
A:Set集合存儲和迭代
/*
* Set接口,特點不重復(fù)元素,沒索引
*
* Set接口的實現(xiàn)類,HashSet (哈希表)
* 特點: 無序集合,存儲和取出的順序不同,沒有索引,不存儲重復(fù)元素
* 代碼的編寫上,和ArrayList完全一致
*/
public class HashSetDemo {
public static void main(String[] args) {
Set<String> set = new HashSet<String>();
set.add("cn");
set.add("heima");
set.add("java");
set.add("java");
set.add("itcast");
Iterator<String> it = set.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
System.out.println("==============");
for(String s : set){
System.out.println(s);
}
}
}
11哈希表的數(shù)據(jù)結(jié)構(gòu)
A:哈希表的數(shù)據(jù)結(jié)構(gòu):(參見圖解)
加載因子:表中填入的記錄數(shù)/哈希表的長度
例如:
加載因子是0.75 代表:
數(shù)組中的16個位置,其中存入16*0.75=12個元素
如果在存入第十三個(>12)元素,導(dǎo)致存儲鏈子過長,會降低哈希表的性能,那么此時會擴(kuò)充哈希表(在哈希),底層會開辟一個長度為原長度2倍的數(shù)組,把老元素拷貝到新數(shù)組中,再把新元素添加數(shù)組中
當(dāng)存入元素數(shù)量>哈希表長度*加載因子,就要擴(kuò)容,因此加載因子決定擴(kuò)容時機(jī)
12字符串對象的哈希值
A:字符串對象的哈希值
/*
* 對象的哈希值,普通的十進(jìn)制整數(shù)
* 父類Object,方法 public int hashCode() 計算結(jié)果int整數(shù)
*/
public class HashDemo {
public static void main(String[] args) {
Person p = new Person();
int i = p.hashCode();
System.out.println(i);
String s1 = new String("abc");
String s2 = new String("abc");
System.out.println(s1.hashCode());
System.out.println(s2.hashCode());
/*System.out.println("重地".hashCode());
System.out.println("通話".hashCode());*/
}
}
//String類重寫hashCode()方法
//字符串都會存儲在底層的value數(shù)組中{'a','b','c'}
public int hashCode() {
int h = hash;//hash初值為0
if (h == 0 && value.length > 0) {
char val[] = value;
for (int i = 0; i < value.length; i++) {
h = 31 * h + val[i];
}
hash = h;
}
return h;
}
13哈希表的存儲過程
A:哈希表的存儲過程
public static void main(String[] args) {
HashSet<String> set = new HashSet<String>();
set.add(new String("abc"));
set.add(new String("abc"));
set.add(new String("bbc"));
set.add(new String("bbc"));
System.out.println(set);
}
存取原理:
每存入一個新的元素都要走以下三步:
1.首先調(diào)用本類的hashCode()方法算出哈希值
2.在容器中找是否與新元素哈希值相同的老元素,
如果沒有直接存入
如果有轉(zhuǎn)到第三步
3.新元素會與該索引位置下的老元素利用equals方法一一對比
一旦新元素.equals(老元素)返回true,停止對比,說明重復(fù),不再存入
如果與該索引位置下的老元素都通過equals方法對比返回false,說明沒有重復(fù),存入