Java 中 Set/HashSet 的内部工作原理

javaobject oriented programmingprogramming

Set 数据结构仅用于存储唯一值,这意味着集合中不会存储重复的值。创建 HashSet 时,它会在内部实现 HashMap。可以使用 ‘add’ 函数将元素插入 HashSet。这在内部调用 ‘put’ 函数,因为 HashMap 是在内部创建的。因此,Set 借助 HashMap 接收唯一值。

HashMap 包含唯一的键和值对,其中使用 ‘put’ 函数插入键和值对。调用 ‘put’ 函数后,函数,根据是否存在键的映射,返回与键关联的先前值或 null。

LinkedHashSet 扩展为 HashSet 类,这意味着 LinkedHashSet 使用 ‘super’ 函数调用 HashSet 类的构造函数。

示例

import java.util.HashSet;
public class Demo{
   public static void main(String args[]){
      HashSet my_hashset = new HashSet();
      boolean my_b1 = my_hashset.add("only");
      boolean my_b2 = my_hashset.add("sample");
      boolean my_b3 = my_hashset.add("sample");
      System.out.println("第一个布尔值的值为 " + my_b1);
      System.out.println("第二个布尔值的值为 = "+my_b2);
      System.out.println("第三个布尔值的值为 = "+my_b3);
      System.out.println(my_hashset);
   }
}

输出

第一个布尔值的值为 true
第二个布尔值的值为 = true
第三个布尔值的值为 = false
[only, sample]

名为 Demo 的类包含主函数,其中定义了 HashSet 的实例。使用 ‘add’ 函数将元素添加到哈希集中。然后这些元素显示在屏幕上。


相关文章