集合数据结构仅用于存储唯一值,这意味着不会在集合中存储重复的值。创建HashSet时,它将在内部实现HashMap。可以使用“添加”功能将元素插入HashSet中。由于HashMap是在内部创建的,因此在内部调用“ put”功能。因此,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("第一个 boolean 是 " + my_b1); System.out.println("第二个 boolean 是 = "+my_b2); System.out.println("第三个 boolean 是 = "+my_b3); System.out.println(my_hashset); } }
输出结果
第一个 boolean 是 true 第二个 boolean 是 = true 第三个 boolean 是 = false [only, sample]
名为Demo的类包含定义HashSet实例的主要功能。使用“add”方法将元素添加到哈希集中。这些元素然后显示在屏幕上。