【2】HashSet使用方法大全!!!

基本用法

(1) boolean add(type);            给指定集合添加一个元素
(2) boolean contains(Object obj);      如果hashSet中存在指定元素,contains()方法成功返回true
(3) boolean remove(Object obj);       删除元素obj并返回true,若不存在返回false
(4) boolean isEmpty();            判断set是否为空集合,为空返回true
(5) int size();                返回集合中存在的元素数量
(6) void clear();              删除引用集合中存在的所有值,成为空集合
import java.util.*;
public class NewTips {
    public static void main(String[] args) {
        // 初始化
        HashSet<Integer> set = new HashSet<>();

        System.out.println("----------add:--------");
        System.out.println(set.add(1));
        System.out.println(set.add(99));
        System.out.println(set.add(78));
        System.out.println(set.add(1));
        System.out.println("显示set: "+set);

        System.out.println("--------contains:------");
        System.out.println(set.contains(1));
        System.out.println(set.contains(2));

        System.out.println("---------remove:-------");
        System.out.println(set.remove(1));
        System.out.println(set.remove(1));

        System.out.println("---------isEmpty:-------");
        System.out.println(set.isEmpty());

        System.out.println("---------size:-------");
        System.out.println(set.size());

        System.out.println("---------clear:-------");
        set.clear();
        System.out.println("显示set: "+set);
    }
}

数据遍历

(1)forEach()

(2)forEachRemaining()

(3)迭代器使用

(4)for循环

import java.util.*;
public class NewTips {
    public static void main(String[] args) {
        // 初始化
        HashSet<Integer> set = new HashSet<>();
        for(int i=0; i<100; i+=15){
            set.add(i);
        }
        System.out.println("显示set: "+set);

        System.out.println("方法一: forEach");
        set.forEach(e->System.out.print(e+"  "));
        System.out.println();

        System.out.println("方法二: forEachRemaining");
        Iterator<Integer> iter1 = set.iterator();
        iter1.forEachRemaining(e->System.out.print(e+"  "));
        System.out.println();

        System.out.println("方法三: iterator");
        Iterator<Integer> iter2 = set.iterator();
        while (iter2.hasNext()) {
            System.out.print(iter2.next()+"  ");
        }
        System.out.println();

        System.out.println("方法四: for");
        for(Integer e : set){
            System.out.print(e+"  ");
        }

    }
}

 

做一个优秀的程序媛
原文地址:https://www.cnblogs.com/oytt/p/14143054.html