Java中的Set集合
Set介面簡介
Set介面和List介面一樣,同樣繼承自Collection介面,它與Collection介面中的方法基本一致,並沒有對Collection介面進行功能上的擴充,它是比Collection介面更加嚴格了。與List介面不同的是,Set介面元素無序,並且都會以某種規則保證存入的元素不出現重複。
Set介面主要有兩個實現類,分別是HashSet和TreeSet。其中,HashSet根據物件的雜湊值來確定元素在集合中的儲存位置,因此具有良好的存取和查詢效能。TreeSet則是以二叉樹的方式來儲存元素,它可以實現對集合中的元素進行排序
HashSet集合
HashSet是Set介面的一個實現類,它所儲存的元素是不可重複的,並且元素都是無序的。當向HashSet集合中新增一個物件時,首先會呼叫該物件的hashCode()方法來計算物件的雜湊值,從而確定元素的儲存位置。如果此雜湊值相同,再呼叫物件的equals()方法來確保該位置沒有重複元素。Set集合與List集合存取元素的方式都一樣。
通過一個案例來演示HashSet集合的用法:
public class Example01 { public static void main(String[] args) { HashSet set = new HashSet(); set.add("老大"); set.add("老二"); set.add("老三"); set.add("老二"); Iterator it = set.iterator(); while(it.hasNext()) { Object obj = it.next(); System.out.println(obj); } } }
結 論:
當向集合中存入元素時,為了保證HashSet正常工作,要求在存入物件時,重寫Object類中的hashCode和equals()方法。
上述案例將字串存入HashSet時,String類已經重寫了hashCode()和equals()方法。但是如果將Student物件存入HashSet,結果又會怎樣呢?
class Student{ String id; String name; public Student(String id, String name) { super(); this.id = id; this.name = name; } @Override public String toString() { return id+":"+name; } @Override public int hashCode() { return id.hashCode(); //返回id屬性的雜湊值 } @Override public boolean equals(Object obj) { if(this == obj) { //判斷是否是同一個物件 return true; //如果是,直接返回true } if(!(obj instanceof Student)) { //判斷物件是為Student型別 return false; //如果物件不是Student型別返回false } Student stu = (Student) obj; //將物件強轉為Student型別 boolean b = this.id.equals(stu.id); //判斷id值是否相同 return b; //返回判斷結果 } } public class Example02 { public static void main(String[] args) { HashSet set = new HashSet(); set.add(new Student("1", "老王")); set.add(new Student("2", "老三")); set.add(new Student("2", "老三")); System.out.println(set); } }
Student類重寫了Object類的hashCode()和equals()方法。在hashCoded()方法中返回id屬性的雜湊值,在equals()方法中比較物件的id屬性是否相等,並返回結果。當呼叫HashSet集合的add()方法新增stu3物件時,發現它的雜湊值與stu2物件相同,而且stu2.equals(stu3)返回true。HashSet集合認為兩個物件相同,因此重複的Student物件對成功去除了。