HashSet小试牛刀

HashSet详细介绍

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

public class Main {

    public static void main(String[] args) {
        HashSet set=new HashSet();
        set.add("a");
        set.add("b");
        set.add("c");
        set.add("d");
        set.add("e");
        Iterator ite=set.iterator();
        System.out.print("通过Iterator遍历HashSet: ");
        while(ite.hasNext()){
            System.out.print(ite.next()+" ");
        }
        System.out.println();
        System.out.print("HashSet的大小: ");
        System.out.println(set.size());
        System.out.print("HashSet是否包含元素1: ");
        System.out.println(set.contains(1));
        System.out.print("HashSet是否包含元素a: ");
        System.out.println(set.contains("a"));
        set.remove("b");
        String array[]=(String [])set.toArray(new String[0]);    //将HashSet变换为数组
        System.out.print("将元素b从set中移除后: ");
        for(String str:array){
            System.out.print(str);
        }
        System.out.println();
        HashSet otherset=new HashSet();
        otherset.add("a");
        otherset.add("c");
        otherset.add("e");
        
        HashSet removeset=(HashSet)set.clone();    //克隆
        removeset.removeAll(otherset);
        System.out.println(removeset);
        
        HashSet retainset=(HashSet)set.clone();
        retainset.retainAll(otherset);
        System.out.println(retainset);
    }

}

输出

通过Iterator遍历HashSet: a b c d e 
HashSet的大小: 5
HashSet是否包含元素1: false
HashSet是否包含元素a: true
将元素b从set中移除后: acde
[d]
[a, c, e]

21:54:31

2019-02-28

posted @ 2019-02-28 21:55  一转身已万水千山  阅读(127)  评论(0编辑  收藏  举报