Java教程

Java HashSet size()

Java HashSet类的 size()方法用于获取此HashSet中的元素数(其基数)。

语法

以下是 size()方法的声明:
public int size()

参数

此方法不接受任何参数。

返回

size()方法返回HashSet中存在的元素数。

异常

NA

兼容性版本

Java 1.2及更高版本

示例1

import java.util.*;
public class HashSetSizeExample1 {
    public static void main(String[] args) {
        HashSet<String> set=new HashSet<String>();
        set.add("Ravi");
        set.add("Vijay");
        set.add("Mohan");
        set.add("Ajay");
        System.out.println("HashSet: " + set);
        System.out.println("The size of the set is: " + set.size());
    }
}
输出:
HashSet: [Vijay, Mohan, Ravi, Ajay]
The size of the set is: 4

示例2

import java.util.*;
public class HashSetSizeExample2 {
    public static void main(String[] args) {
        HashSet <Integer> hashSetObject = new HashSet <>();
        hashSetObject.add(45);
        hashSetObject.add(-67);
        hashSetObject.add(98);
        int s = hashSetObject.size();
        System.out.println("Size of HashSet is: "+s);
    }
}
输出:
Size of HashSet is: 3

示例3

import java.util.*;
public class HashSetSizeExample3 {
    public static void main(String[] args) {
        HashSet studentSet = init();
        int size = studentSet.size();
        System.out.println("Size of student database is: "+size);
    }
    private static HashSet init() {
        HashSet<String> studentSet = new HashSet<>();
        studentSet.add("Peter");
        studentSet.add("Watson");
        studentSet.add("Desuja");
        studentSet.add("Kevin");
        return studentSet;
    }
}
输出:
Size of student database is: 4

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