• Index

HashSet 实现类

Last updated: ... / Reads: 44 Edit

HashSet 是 Java 中 Set 接口的一个实现类,它基于哈希表(hash table)实现。它提供了存储唯一元素的集合,并且不保证元素的顺序。下面是一个简单的示例代码,展示如何使用 HashSet:

import java.util.HashSet;

public class HashSetExample {
    public static void main(String[] args) {
        // 创建一个 HashSet 对象
        HashSet<String> set = new HashSet<>();

        // 添加元素到 HashSet
        set.add("Apple");
        set.add("Banana");
        set.add("Orange");

        // 打印 HashSet 的内容
        System.out.println("HashSet: " + set);

        // 检查元素是否存在于 HashSet
        System.out.println("Contains 'Apple': " + set.contains("Apple"));

        // 删除元素从 HashSet
        set.remove("Banana");

        // 打印更新后的 HashSet 的内容
        System.out.println("Updated HashSet: " + set);
    }
}

输出结果应该为:

HashSet: [Orange, Apple, Banana]
Contains 'Apple': true
Updated HashSet: [Orange, Apple]

HashSet不保证元素的顺序,因此每次运行程序时,元素的顺序可能会有所变化。 HashSet在添加、删除和查找元素方面具有很高的性能,适用于需要快速访问和唯一性约束的场景。


Comments

Make a comment

  • Index