Java中的HashSet

HashSet扩展AbstractSet并实现Set接口。它创建一个使用哈希表进行存储的集合。

哈希表通过使用称为哈希的机制来存储信息。在散列中,键的信息内容用于确定唯一值,称为其散列码。

然后,将哈希码用作存储与键关联的数据的索引。键到其哈希码的转换是自动执行的。

示例

让我们看一个在Java中实现HashSet的示例-

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      HashSet <String> hashSet = new HashSet <String>();
      hashSet.add("One");
      hashSet.add("Two");
      hashSet.add("Three");
      hashSet.add("Four");
      hashSet.add("Five");
      hashSet.add("Six");
      System.out.println("Hash set values = "+ hashSet);
   }
}

输出结果

Hash set values = [Five, Six, One, Four, Two, Three]

示例

让我们看看另一个示例,从HashSet中删除元素-

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      HashSet <String> newset = new HashSet <String>();
      newset.add("Learning");
      newset.add("Easy");
      newset.add("Simply");
      System.out.println("Values before remove: "+newset);
      boolean isremoved = newset.remove("Easy");
      System.out.println("Return value after remove: "+isremoved);
      System.out.println("Values after remove: "+newset);
   }
}

输出结果

Values before remove: [Learning, Easy, Simply]
Return value after remove: true
Values after remove: [Learning, Simply]