Java教程

Java HashSet clear()

Java HashSet类的 clear()方法用于从该集合中删除所有元素。

语法

以下是 clear()方法的声明:
public void clear()

参数

此方法不接受任何参数。

返回

clear()方法不会返回任何值。

例外:

NA

兼容版本

Java 1.2及更高版本

示例1

import java.util.*;
public class HashSetClearExample1 {
    public static void main(String[] args) {
        HashSet<String>hset = new HashSet<String>();
        hset.add("JTP");
        hset.add("SSSIT");
        hset.add("DFC");
        System.out.println("Hash set Elements: "+ hset);
        hset.clear();
        System.out.println("Hash set elements after clear: "+ hset);
    }
}
输出:
Hash set Elements: [DFC, SSSIT, JTP]
Hash set elements after clear: []

示例2

import java.util.*;
public class HashSetClearExample2 {
    public static void main(String[] args) {
        HashSet<Integer> hset = new HashSet<Integer>();
        hset.add(121);
        hset.add(111);
        hset.add(151);
        System.out.println("Hash set Elements: "+ hset);
        hset.clear();
        System.out.println("Hash set elements after clear: "+ hset);
    }
}
输出:
Hash set Elements: [151, 121, 111]
Hash set elements after clear: []

示例3

import java.util.*;
public class HashSetClearExample3 {
    public static void main(String[] args) {
        HashSet<String> hset1 = new HashSet<String>();
        HashSet hset1.add("Facebook");
        hset1.add("Twitter");
        hset1.add("Instagram");
        hset1.add("Google");
        System.out.println("Size of the HashSet: "+hset1.size());
        System.out.println("Elements of the HashSet before clear:");
        for(String val : hset1)
            {
            System.out.println(val);
        }
        hset1.clear();
        System.out.println("Elements of the HashSet after clear:");
        System.out.println("Size of the hashset: "+hset1.size());
        for(String val : hset1)
            {
            System.out.println(val);
        }
    }
}
输出:
Size of the HashSet: 4
Elements of the HashSet before clear:
Google
Twitter
Instagram
Facebook
Elements of the HashSet after clear:
Size of the hashset: 0

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