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);
  }
}

猜你喜欢

转载自blog.csdn.net/OliverZang/article/details/84875648