Java中 HashSet與HasnMap區別和方法

HashSet與HasnMap區別和方法


區別:

1. HashSet是通過HashMap實現的,TreeSet是通過TreeMap實現的,只不過Set用的只是Map的key 
2.  Map的key和Set都有一個共同的特性就是集合的唯一性.TreeMap更是多了一個排序的功能.
3.  hashCode和equal()是HashMap用的, 因爲無需排序所以只需要關注定位和唯一性即可.
 a. hashCode是用來計算hash值的,hash值是用來確定hash表索引的.
b. hash表中的一個索引處存放的是一張鏈表, 所以還要通過equal方法循環比較鏈上的每一個對象 纔可以真正定位到鍵值對應的Entry. 
c. put時,如果hash表中沒定位到,就在鏈表前加一個Entry,如果定位到了,則更換Entry中的value,並返回舊value 
4. 由於TreeMap需要排序,所以需要一個Comparator爲鍵值進行大小比較.當然也是用Comparator定位的. 
a. Comparator可以在創建TreeMap時指定 

b. 如果創建時沒有確定,那麼就會使用key.compareTo()方法,這就要求key必須實現Comparable接口.


TreeMap是使用Tree數據結構實現的,所以使用compare接口就可以完成定位了. 


方法:

HashSet的使用 
 
package edu.love;
import java.util.HashSet;
import java.util.Iterator;
public class WpsklHashSet { 
//java 中Set的使用(不允許有重複的對象):
public static void main(String[] args) {
HashSet hashSet=new HashSet(); 
String a=new String("A"); 
String b=new String("B"); 
String c=new String("B");
hashSet.add(a);
hashSet.add(b);
System.out.println(hashSet.size()); 
 
String cz=hashSet.add(c)?"此對象不存在":"已經存在";
System.out.println("測試是否可以添加對象 "+cz); 
System.out.println(hashSet.isEmpty());
//測試其中是否已經包含某個對象 
System.out.println(hashSet.contains("A"));
 
Iterator ir=hashSet.iterator(); 
while(ir.hasNext()) { 
System.out.println(ir.next());
}  //測試某個對象是否可以刪除 
System.out.println(hashSet.remove("a"));
System.out.println(hashSet.remove("A")); 
//經過測試,如果你想再次使用ir變量,必須重新更新以下 
ir=hashSet.iterator(); 
while(ir.hasNext()) {
System.out.println(ir.next()); 
}


 
TreeSet的使用 
 
import java.util.TreeSet;
import java.util.Iterator; 
public class TreeSetTest {
public static void main(String[] args) { 
TreeSet tree = new TreeSet();
tree.add("China");
tree.add("America");
tree.add("Japan"); 
tree.add("Chinese"); 
Iterator iter = tree.iterator();
while(iter.hasNext()) { 
System.out.println(iter.next()); 
}

發佈了32 篇原創文章 · 獲贊 2 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章