Java HashSet isEmpty() 方法

isEmpty() 用于判断HashSet是否包含元素(是否为空)。如果集合包含元素,则返回true,否则返回false。

1 语法

public boolean isEmpty()  

2 参数

3 返回值

如果HashSet不包含元素返回true,否则返回false。

4 HashSet isEmpty()示例1

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java HashSet.isEmpty()方法的例子
 */
import java.util.*;

public class Demo {

    public static void main(String[] args) {

        //创建HashSet
        HashSet<String> hset = new HashSet<String>();
        //添加元素
        hset.add("Welcome");
        hset.add("To");
        hset.add("Yiidian");
        //输出HashSet
        System.out.println("HashSet元素为: "+hset);
        //判断HashSet是否为空
        System.out.println("Is the set empty: "+hset.isEmpty());
        //清空HashSet
        hset.clear();
        System.out.println("Is the set empty: "+hset.isEmpty());
    }
}

输出结果为:

HashSet元素为: [Yiidian, Welcome, To]
Is the set empty: false
Is the set empty: true

5 HashSet isEmpty()示例2

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java HashSet.isEmpty()方法的例子
 */
import java.util.*;

public class Demo {

    public static void main(String[] args) {
        HashSet <Integer> hashSetObject = new HashSet <>();
        hashSetObject.add(45);
        hashSetObject.add(67);
        hashSetObject.add(98);
        //判断HashSet是否为空
        boolean b1 = hashSetObject.isEmpty();
        System.out.println("Is hash set empty?:- "+b1);
        System.out.println("HashSet元素为: "+hashSetObject);
        //清空HashSet
        hashSetObject.clear();
        boolean b2 = hashSetObject.isEmpty();
        System.out.println("Is hash set empty?:- "+b2);
        System.out.println("HashSet元素为: "+hashSetObject);
    }
}

输出结果为:

Is hash set empty?:- false
HashSet元素为: [98, 67, 45]
Is hash set empty?:- true
HashSet元素为: []

6 HashSet isEmpty()示例3

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java HashSet.isEmpty()方法的例子
 */
import java.util.*;

public class Demo {

    public static void main(String[] args) {
        //初始化HashSet对象
        HashSet studentSet = init();
        //判断是否为空
        if(studentSet.isEmpty()){
            System.out.println("student database is empty: "+studentSet);
        }
        else{
            System.out.println("student database has "+studentSet.size()+" names: "+studentSet);
        }
        studentSet.clear();
        if(studentSet.isEmpty()){
            System.out.println("student database is empty: "+studentSet);
        }
        else{
            System.out.println("student database has "+studentSet.size()+" names: "+studentSet);
        }
    }
    private static HashSet init() {
        //初始化HashSet
        HashSet<String> studentSet = new HashSet<>();
        studentSet.add("eric");
        studentSet.add("jack");
        studentSet.add("rose");
        return studentSet;
    }
}

输出结果为:

student database has 3 names: [eric, rose, jack]
student database is empty: []

 

热门文章

优秀文章