1. 程式人生 > >Java:HashSet操作練習

Java:HashSet操作練習

HashSet繼承AbstractSet類, 實現Set,Cloneable,Serializable介面。

初始化HashSet等於初始化一個內部成員HashMap map,預設容量16,負載因子0.75

操作HashSet的元素等於用元素作為HashMap的key操作map
iterator()==map.keySet().iterator()

add(E) ==map.put(E,Final_Object)

remove(E)==map.remove(E)

import java.util.*;

/*
 * This class is meant to practise implementing the API of HashSet
 */
@SuppressWarnings("unchecked") public class HashSetPrac{ public static void main(String[] args){ //1.instantiate a HashSet var hashSet = new HashSet(); //using other constructors var hashSet2 = new HashSet(new LinkedList<Integer>()); var hashSet3 = new HashSet(32); //initialCapacity
var hashSet4 = new HashSet(32,0.75f); //plus loadFactor //2. add data print("==========2========="); for(int i=1;i<=100;i++){ hashSet.add(i); } print(hashSet); print(hashSet.size()); //3.traverse the set,get the largest number print("==========3========="); int
max=Integer.MIN_VALUE; int element = max; //while iterator var iterator = hashSet.iterator(); while (iterator.hasNext()){ element = (Integer)iterator.next(); if (max < element){ max = element; } } print(max); //4.travese the set, print all elements print("==========4========="); //iterator for(iterator= hashSet.iterator();iterator.hasNext();){ System.out.print(iterator.next() + ","); } print(""); //for each Integer[] arr = (Integer[])hashSet.toArray(new Integer[0]); for(Integer e:arr){ System.out.print(e + ","); } print(""); //5.clone,retainAll,removeAll print("==========5========="); //copy hashSet then add data to copy var copy = (HashSet)hashSet.clone(); var copy2 = (HashSet)hashSet.clone(); for(int i=0;i>-100;i--){ copy.add(i); copy2.add(i); } //remove contents of which hashSet contains from copy copy.removeAll(hashSet); //retain contents of which hashSet contains for copy copy2.retainAll(hashSet); print(copy); // has no positive values print(copy2); //has no negative values //6.remove,clear print("==========6========="); for (int i=-99;i<-50;i++){ copy.remove(i); } print(copy); copy.clear(); print(copy); } public static void print(Object obj){ System.out.println(obj); } }