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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值