Java教程

Java HashSet isEmpty()方法

Java HashSet isEmpty()方法

Java HashSet类的 isEmpty()方法用于检查是否HashSet包含元素。如果集合包含元素,则返回true,否则返回false。

语法

以下是 isEmpty()方法的声明:
public boolean isEmpty()

参数

此方法不接受任何参数。

返回

isEmpty()方法如果该集合不包含任何元素,则返回true。

异常

NA

兼容性版本

Java 1.2及更高版本

示例1

import java.util.*;
public class HashSetIsEmptyExample1 {
    public static void main(String[] args) {
        HashSet<String> hset = new HashSet<String>();
        hset.add("Welcome");
        hset.add("To");
        hset.add("lidihuo");
        System.out.println("HashSet Elements: "+hset);
        System.out.println("Is the set empty: "+hset.isEmpty());
        hset.clear();
        System.out.println("Is the set empty: "+hset.isEmpty());
    }
}
输出:
HashSet Elements: [Welcome, To, lidihuo]
Is the set empty: false
Is the set empty: true

示例2

import java.util.*;
public class HashSetIsEmptyExample2 {
    public static void main(String[] args) {
        HashSet <Integer> hashSetObject = new HashSet <>();
        hashSetObject.add(45);
        hashSetObject.add(67);
        hashSetObject.add(98);
        boolean b1 = hashSetObject.isEmpty();
        System.out.println("Is hash set empty?:- "+b1);
        System.out.println("HashSet Element: "+hashSetObject);
        hashSetObject.clear();
        boolean b2 = hashSetObject.isEmpty();
        System.out.println("Is hash set empty?:- "+b2);
        System.out.println("HashSet Element: "+hashSetObject);
    }
}
输出:
Is hash set empty?:- false
HashSet Element: [98, 67, 45]
Is hash set empty?:- true
HashSet Element: []

示例3

import java.util.*;
public class HashSetIsEmptyExample3 {
    public static void main(String[] args) {
        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<String> studentSet = new HashSet<>();
        studentSet.add("Rahul");
        studentSet.add("Mohan");
        studentSet.add("Karan");
        return studentSet;
    }
}
输出:
student database has 3 names: [Rahul, Mohan, Karan]
student database is empty: []

昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4