【集合】HashSet類

HashSet類實現Set接口,該類使用散列表對數據進行存儲。

HashSet在進行數據存儲時不保證數據的有序性,並且存儲是變化的,同時運行保存null。

import java.util.HashSet;
import java.util.Iterator;

public class HashSetDemo {
	public static void main(String[] args) {
		
		HashSet hs = new HashSet();		
		hs.add(new Integer(65));
		hs.add("A");
		hs.add(Integer.valueOf(65));
		hs.add("B");
		hs.add(Integer.valueOf(98));
		hs.add("a");
		hs.add(Integer.valueOf(99));
		hs.add("b");
		//System.out.println("HashSet:" + hs);
		
		print(hs);
		System.out.println("HashSet的長度:" + hs.size());
		System.out.println("HashSet是否爲空:" + hs.isEmpty());
		//移除元素
		hs.remove("A");
		hs.remove(99);		
		print(hs);
		
	}
	
	public static void print(HashSet hashSet){
		Iterator it = hashSet.iterator();
		while(it.hasNext()){			
			System.out.print(it.next() + " ,");
		}
		System.out.println();		
		System.out.println("--------------------------");
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章