集合Set:實現了collection接口
確定性:對任意對象都能夠判定是否屬於某一個集合
互異性:集合內的每個單元都是無差異的,注意是內容無差異
無序性:集合內的順序無關
Java中的集合接口Set:
-- HashSet(基於三列函數的集合,無序,不支持同步)
--TreeSet(基於樹結構的集合,可排序的,不支持同步)
--LinkedHashSet(基於三列函數和雙向鏈表的集合,可排序的,不支持同步)
*HashSet,linkedHashSet,TreeSet 的元素都只能夠是對象
- HashSet和LinkedHashSet判定元素重複的原則
1.判斷兩個元素的hashCode返回值是否是相同,若不同,返回false
2.若兩者的hashCode返回值相同,判定equals方法,若不同,返回false,否則返回true
- TreeSet判定元素重複的原則:
- 需要元素實現Comparable接口
- 比較兩個元素的compareTo方法
=================================分割線=================================
HashSet:
- 基於HashMap實現的,可以容納null元素,不支持同步 (若要實現同步:Set s=Collections.synchronizedSet(new HashSet(…));)
- add 添加一個元素
- clear 清除整個HashSet
- contains 判定是否包含某一個元素
- remove 刪除某一個元素
- size大小
- retainAll 計算兩個集合交集
import java.util.HashSet;
import java.util.Iterator;
public class HashSet_test {
public static void main(String[] args) {
// TODO Auto-generated method stub
HashSet<Integer> hs=new HashSet();
boolean bool=hs.add(0);
System.out.println("HashSet添加一個不重複的值,結果:"+bool);
hs.add(1);
hs.add(2);
hs.add(3);
boolean bool1=hs.add(null);
System.out.println("HashSet添加null值,結果:"+bool1);
boolean bool2=hs.add(3);
System.out.println("HashSet添加相同元素 ,結果:"+bool2);
Iterator itemr=hs.iterator();
while(itemr.hasNext()){
System.out.println(itemr.next());
}
hs.remove(1);
System.out.println("--------分割線-----------");
Iterator itemr2=hs.iterator();
while(itemr2.hasNext()){
System.out.println(itemr2.next());
}
}
}
================================分割線=================================
LinkedHashSet:
- 繼承HashSet,也是預計HashMap實現的,可以容納null元素
- 不支持同步 (若要實現同步:Set s=Collections.synchronizedSet(new LinkedHashSet(…));)
- 方法和HashSet基本一致
- add、clear、contains、remove、size
- 通過一個雙向鏈表維護插入順序
==============================分割線=====================================
TreeSet:
- 基於TreeMap實現,不可以容納null元素(若要實現同步:SortedSet s=Collections.synchronizedSortedSet(new TreeSet(…));)
- add添加一個元素
- clear清除整個TreeSet
- contains判斷是否包含某一個元素
- remove刪除某一個元素
- size大小
- 根據compareTo方法指定Comparator排序