下面是一个创建 HashSet 集合的代码示例:

import java.util.HashSet;
import java.util.Arrays;
import java.util.Set;

public class HashSetExample {
    public static void main(String[] args) {
        // 创建一个空的 HashSet 集合
        HashSet<String> set1 = new HashSet<>();

        // 创建一个包含指定元素的 HashSet 集合
        HashSet<Integer> set2 = new HashSet<>(Set.of(1, 2, 3, 4, 5));

        // 创建一个包含指定数组元素的 HashSet 集合
        String[] array = {'apple', 'banana', 'orange'};
        HashSet<String> set3 = new HashSet<>(Arrays.asList(array));

        // 输出 HashSet 集合的元素
        System.out.println(set1); // 输出:[]
        System.out.println(set2); // 输出:[1, 2, 3, 4, 5]
        System.out.println(set3); // 输出:[apple, banana, orange]
    }
}

在上面的示例中,我们创建了三个不同的 HashSet 集合。第一个集合 'set1' 是一个空集合,第二个集合 'set2' 包含了整数 1 到 5,第三个集合 'set3' 包含了字符串数组中的元素。最后,我们使用 'System.out.println()' 方法打印出了每个 HashSet 集合的元素。

Java HashSet 集合创建代码示例

原文地址: https://www.cveoy.top/t/topic/bUwH 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录