標籤:size map list source turn height system 樹結構 相同
Set集合
Set和Collection基本相同,Set不允許有重複元素,集合內的元素是無序的。
1) HashSet類
特點:不能保證元素的排列順序、不是同步的,多線程操作時需要通過代碼保證其同步性、集合元素值可以為null。HashSet添加原始的時候根據元素的hashCode值來計算 它的儲存位置,方便快速該元素。(hash演算法的功能是保證快速尋找被檢索的對象,根據元素的hashcode值計算該元素的儲存位置,從而快速定位元素位置。)
HashSet判斷元素是否相等通過equals()方法相等,並且hashCode()方法傳回值也必須相等。
程式碼範例:
/** * 重寫equals方法,不重寫hashcode方法 * @author Administrator * */public class Demo1 { @Override public boolean equals(Object obj) { return true; }} /** * 重寫hashcode方法,不重寫equals方法 * @author Administrator * */public class Demo2 { @Override public int hashCode() { return 1; }} /** * 重寫equals方法和hashcode方法 * @author Administrator * */public class Demo3 { @Override public boolean equals(Object obj) { return true; } @Override public int hashCode() { return 2; }} public class HashSetDemo { public static void main(String[] args) { HashSet ss = new HashSet(); // 插入equals方法相等的兩個對象 ss.add(new Demo1()); ss.add(new Demo1()); // 插入hashcode相等的兩個對象 ss.add(new Demo2()); ss.add(new Demo2()); // 插入equals和hashcode相等得對象 ss.add(new Demo3()); ss.add(new Demo3()); // 輸出結果 System.out.println(ss); }}
輸出結果是:
[[email protected], [email protected], [email protected], [email protected], [email protected]]
上述輸出結果表示HashSet判斷元素相等必須equals方法和hashcode方法傳回值必須相等,如demo3類
HashSet基本使用程式碼範例:
public class HashSetTest { public static void main(String[] args) { Set<String> hashSet = new HashSet<String>(); // 添加元素 hashSet.add("Set集合"); hashSet.add("List集合"); hashSet.add("Map集合"); // 刪除元素 hashSet.remove("Map集合"); // 遍曆元素 for (String string : hashSet) { System.out.println(string); } Iterator<String> iter = hashSet.iterator(); while (iter.hasNext()) { String str= (String) iter.next(); System.out.println(str); } }}
2)TreeSet類
特點:使用紅/黑樹狀結構結構儲存元素、元素是有序的、支援兩種排序方法,自然排序和定製排序,treeSet只能添加一種類型的Object Storage Service元素時對象必須重寫Comparable介面中得compareTo(Object obj)方法,否則引發ClassCastException異常。TreeSet集合判斷兩個對象是否相等,是通過compareTo(Object obj)方法比較是否返回0,返回0則相等,否則則不相等。
public class Test{} public class TreeSetTest { public static void main(String[] args) { Set treeSet = new TreeSet(); treeSet.add(new Test()); treeSet.add(new Test()); System.out.println(treeSet); }}
輸出結果:
Exception in thread "main" java.lang.ClassCastException: com.zzl.demo.Test cannot be cast to java.lang.Comparable at java.util.TreeMap.compare(Unknown Source) at java.util.TreeMap.put(Unknown Source) at java.util.TreeSet.add(Unknown Source) at com.zzl.demo.TreeSetTest.main(TreeSetTest.java:10)
總結:因為TreeSet需要額外的紅/黑樹狀結構演算法來維護元素的次序,所以TreeSet的效能不如HashSet;當需要保持排序的Set時,使用TreeSet,否則建議使用HashSet。
Java 集合知識總結(二)