原文: https://beginnersbook.com/2014/08/hashset-vs-hashmap-java/
在本文中,我们将讨论HashSet和HashMap类之间的差异。
HashSet vs HashMap
差异:
HashSet |
HashMap |
|---|---|
HashSet类实现Set接口 |
HashMap类实现了Map接口 |
在HashSet中,我们存储对象(元素或值),例如如果我们有一个字符串元素的HashSet,那么它可以描述一组HashSet元素:{"Hello", "Hi", "Bye", "Run"} |
HashMap用于存储键值对。简而言之,它保持了键和键的映射。(HashMap类大致相当于Hashtable,除了它是不同步的并且允许空值。)如果HashMap元素具有整数键和String类型的值,则可以表示HashMap元素:{1->"Hello", 2->"Hi", 3->"Bye", 4->"Run"} |
HashSet不允许重复元素,这意味着您无法在HashSet中存储重复值。 |
HashMap不允许重复键,但它允许重复值。 |
HashSet允许具有单个空值。 |
HashMap允许单个null键和任意数量的空值。 |
相似之处:
1)HashMap和HashSet都不同步,这意味着它们不适合线程安全操作unitl,除非明确同步。这是你可以明确地同步它们的方法:
HashSet:
Set s = Collections.synchronizedSet(new HashSet(...));
HashMap:
Map m = Collections.synchronizedMap(new HashMap(...));
2)这两个类都不保证其元素的顺序会随着时间的推移保持不变。
3)如果查看HashSet的源代码,您可能会发现它由HashMap备份。所以基本上它在内部使用HashMap进行所有操作。
4)它们都为基本操作提供恒定的时间性能,例如添加,删除元素等。
HashSet示例
import java.util.HashSet;class HashSetDemo{public static void main(String[] args) {// Create a HashSetHashSet<String> hset = new HashSet<String>();//add elements to HashSethset.add("AA");hset.add("BB");hset.add("CC");hset.add("DD");// Displaying HashSet elementsSystem.out.println("HashSet contains: ");for(String temp : hset){System.out.println(temp);}}}
输出:
HashSet contains:AABBCCDD
HashMap示例
import java.util.HashMap;class HashMapDemo{public static void main(String[] args) {// Create a HashMapHashMap<Integer, String> hmap = new HashMap<Integer, String>();//add elements to HashMaphmap.put(1, "AA");hmap.put(2, "BB");hmap.put(3, "CC");hmap.put(4, "DD");// Displaying HashMap elementsSystem.out.println("HashMap contains: "+hmap);}}
输出:
HashMap contains: {1=AA, 2=BB, 3=CC, 4=DD}
