1. 程式人生 > >集合框架之Set HashSet

集合框架之Set HashSet

getc 運行 就是 實現 原理 pan object ret boolean

HashSet是Set接口的實現類,其底層數據結構為哈希表。

HashSet是線程不安全的(不保證同步)。

HashSet優點:添加、刪除、查詢效率高。

    缺點:無序

    哈希表的工作原理:

  首先,拿到元素,計算元素的HashCode值,使用根據y=K(x)的哈希函數計算出元素的存儲位置,如果該位置沒有元素,則將元素存放到該位置。如果該位置上已經存在元素,則使用equals方法比較元素的內容是否相同,如果相同,則不再添加進去,摒棄掉。如果不同,則在同一個位置拉鏈一個空間放置該元素。

  註意1:y代表存儲位置,x代表hashCode值,即哈希碼,y=K(x)的作用是根據哈希碼去計算存儲位置。

  註意2:Integer類型對象的哈希碼就是對象的數值本身。

  註意3:HashSet是無序的,元素是唯一的。

技術分享圖片

     添加自定義對象:

  如果要向HashSet中存儲元素時,元素對象中一定要實現hashCode方法和equals方法,不然會運行報錯。因為根據哈希表原理,存儲時要使用hashCode方法和equals方法進行判斷存儲的位置。

  

 1 package cn.sxt03.hashset;
 2 
 3 public class Student {
 4     private String id;
 5     private
String name; 6 private int age; 7 8 // 9 10 11 @Override 12 public int hashCode() { 13 final int prime = 31; 14 int result = 1; 15 result = prime * result + age; 16 result = prime * result + ((id == null) ? 0 : id.hashCode());
17 result = prime * result + ((name == null) ? 0 : name.hashCode()); 18 return result; 19 } 20 21 @Override 22 public boolean equals(Object obj) { 23 if (this == obj) 24 return true; 25 if (obj == null) 26 return false; 27 if (getClass() != obj.getClass()) 28 return false; 29 Student other = (Student) obj; 30 if (age != other.age) 31 return false; 32 if (id == null) { 33 if (other.id != null) 34 return false; 35 } else if (!id.equals(other.id)) 36 return false; 37 if (name == null) { 38 if (other.name != null) 39 return false; 40 } else if (!name.equals(other.name)) 41 return false; 42 return true; 43 } 44 45 @Override 46 public String toString() { 47 return "Student [id=" + id + ", name=" + name + ", age=" + age + "]"; 48 } 49 50 }

  

集合框架之Set HashSet