java Java集合框架中的Hashtable、HashMap、HashSet、哈希表概念

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47838841/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 09:50:18  来源:igfitidea点击:

Hashtable, HashMap, HashSet , hash table concept in Java collection framework

javahashhashmaphashtablehashset

提问by CuriousMind

I am learning Java Collection Framework and got moderated understanding. Now, when I am going a bit further I got some doubts in: HashMap, HashSet, Hashtable.

我正在学习 Java Collection Framework 并获得了适度的理解。现在,当我更进一步时,我对以下内容产生了一些疑问:HashMap, HashSet, Hashtable

The Javadoc for HashMapsays:

Javadoc forHashMap说:

Hash table based implementation of the Map interface. This implementation provides all of the optional map operations, and permits null values and the null key.

Map接口的基于哈希表的实现。此实现提供了所有可选的映射操作,并允许空值和空键。

The Javadoc for HashSetsays:

Javadoc forHashSet说:

This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time.

这个类实现了 Set 接口,由一个哈希表(实际上是一个 HashMap 实例)支持。它不保证集合的迭代顺序;特别是,它不保证订单会随着时间的推移保持不变。

The Javadoc for Hashtablesays:

Javadoc forHashtable说:

This class implements a hash table, which maps keys to values. Any non-null object can be used as a key or as a value.

这个类实现了一个哈希表,它将键映射到值。任何非空对象都可以用作键或值。

It is confusing that all of them implement the hash table. Do they implement the conceptof hash table?

令人困惑的是,它们都实现了hash table. 难道他们实现概念哈希表

It seems that all these are related to each other, but I am not able to fully understand it.

似乎所有这些都是相互关联的,但我无法完全理解。

Can anyone help me understand this concept in simple language.

谁能帮我用简单的语言理解这个概念。

回答by Ted Hopp

Java's Setand Mapinterfaces specify two very different collection types. A Setis just what it sounds like: a collection of distinct (non-equal) objects, with no other structure. A Mapis, conceptually, just what it sounds like: a mapping from a set of objects (the keys) to a collection of objects (the values). Hashtableand HashMapboth implement Map, HashSetimplements Set, and they all use hash codes for keys/objects contained in the sets to improve performance.

JavaSetMap接口指定了两种截然不同的集合类型。ASet就是它听起来的样子:一组不同(不相等)的对象,没有其他结构。从Map概念上讲,A就是它听起来的样子:从一组对象(键)到一组对象(值)的映射。Hashtable并且HashMap都实现MapHashSet实现Set,并且它们都使用包含在集合中的键/对象的哈希码来提高性能。

Hashtableand HashMap

HashtableHashMap

Hashtableis a legacy class that almost always should be avoided in favor of HashMap. They do essentially the same thing, except most methods in Hashtableare synchronized, making individual method calls thread-safe.1You have to provide your own synchronization or other thread safety mechanism if you are using multiple threads and HashMap.

Hashtable是一个遗留类,几乎总是应该避免使用HashMap. 它们基本上做相同的事情,除了大多数方法Hashtable是同步的,使单个方法调用线程安全。1如果您使用多线程和HashMap.

The problem with Hashtableis that synchronizing each method call (which is a not-insignificant operation) is usually the wrong thing. Either you don't need synchronization at all or, from the point of the view of the application logic, you need to synchronize over transactions that span multiple method calls. Since it was impossible to simply remove the method-level synchronization from Hashtablewithout breaking existing code, the Collections framework authors needed to come up with a new class; hence HashMap. It's also a better name, since it becomes clear that it's a kind of Map.

问题Hashtable在于同步每个方法调用(这是一个无关紧要的操作)通常是错误的。要么您根本不需要同步,要么从应用程序逻辑的角度来看,您需要对跨越多个方法调用的事务进行同步。由于不可能在Hashtable不破坏现有代码的情况下简单地删除方法级同步,因此集合框架作者需要提出一个新类;因此HashMap。这也是一个更好的名字,因为很明显它是一种Map.

Oh, if you do need method-level synchronization, you still shouldn't use Hashtable. Instead, you can call Collections.synchronizedMap()to turn any map into a synchronized one. Alternatively, you can use ConcurrentHashMap, which, according to the docs: "obeys the same functional specification as Hashtable" but has better performance and additional functionality (such as putIfAbsent()).

哦,如果你确实需要方法级同步,你仍然不应该使用Hashtable. 相反,您可以调用Collections.synchronizedMap()将任何地图转换为同步地图。或者,您可以使用ConcurrentHashMap, 根据文档:“遵循与”相同的功能规范,Hashtable但具有更好的性能和附加功能(例如putIfAbsent())。

1There are other differences (less significant, in my view) such as HashMapsupporting nullvalues and keys.

1还有其他差异(在我看来不太重要),例如HashMap支持null值和键。

HashSet

HashSet

In terms of functionality, HashSethas nothing to do with HashMap. It happens to use a HashMapinternally to implement the Setfunctionality. For some reason, the Collections framework developers thought it would be a good idea to make this internal implementation detail part of the public specification for the class. (This was an error, in my view.)

在功能方面,HashSetHashMap. 它恰好在HashMap内部使用 a来实现Set功能。出于某种原因,集合框架开发人员认为将这个内部实现细节作为类的公共规范的一部分是一个好主意。(在我看来,这是一个错误。)

回答by Beefster

Hashtable was an old class that was created before Java had generics. It's only around still for backwards compatibility. Use HashMap instead.

Hashtable 是在 Java 有泛型之前创建的一个旧类。它只是为了向后兼容。改用 HashMap。

Use HashSet when you don't need to map keys to values. It's built on the same algorithm as hash tables, but it is used for a fundamentally different purpose.

当您不需要将键映射到值时,请使用 HashSet。它建立在与哈希表相同的算法上,但用于根本不同的目的。

回答by P.sharma

HashMap and HashTable both inherits Map interface.and have almost same working and properties.But the major differences are as follows:-

HashMap 和 HashTable 都继承了 Map 接口。工作和属性几乎相同。但主要区别如下:-

1.Hashmap is an unordered map of key and value pairs.And we can have the null key or value pairs inside a hashmap.Also a hashmap is unsynchronized(i.e. not thread safe multiple threads can access and modify it at the same time.)But we can externally make a hashmap thread-safe.So if we are not considering the synchronization issues then hashmap is preferable.

1.Hashmap 是一个键值对的无序映射。我们可以在一个 hashmap 里面有空的键或值对。而且一个 hashmap 是不同步的(即不是线程安全的,多个线程可以同时访问和修改它。)但是我们可以在外部使 hashmap 线程安全。所以如果我们不考虑同步问题,那么 hashmap 更可取。

2.HashTable:- A synchronized hashMap(i.e. a thread safe hashmap).But the keys and value pairs in this case never ever be null.In a Hashtable we specify an object that is used as a key, and the value we want to associate to that key. The key is then hashed, and the resulting hash code is used as the index at which the value is stored within the table

2.HashTable:-一个同步的hashMap(即线程安全的hashmap)。但是在这种情况下,键和值对永远不会为空。在Hashtable中,我们指定一个用作键的对象,以及我们想要的值关联到该键。然后对键进行散列,所得散列码用作将值存储在表中的索引

3.HashSet:-A hashset inherits set interface and in the end its also based on hashtable(or we can say deeply connected to our hashmap only)but in this case the key's and values pairs are always unique no duplicate values allowed.but null key values are allowed.Objects are inserted based on their hash code.

3.HashSet:-一个hashset继承了set接口,最后它也基于hashtable(或者我们可以说只与我们的hashmap深度连接)但在这种情况下,键和值对总是唯一的,不允许重复值。但为空键值是允许的。对象是根据它们的哈希码插入的。

In a conclusion we can say all the three collections have connected to Map interface on and all.

总之,我们可以说所有三个集合都已连接到 Map 接口。

回答by Arman Tumanyan

Hashtable is synchronized but HashMap is not, but you can make HashMap synchronize with help of method Collections.synchronizedMap() . Hashtable, HashMap and HashSet are woking based on Hash Table data structure. You can use one null key and which kind of null values you want for HashMap but Hashtable does not allow null key or null values. Basically under HashSet is working HashMap where value is Object hence HashSet values are unique because HashMap keys are unique. So for putting key value pair in Hashmap or Hashtable or putting element to HashSet you need to ovveride hashcode and equals methods from Object class to correct working of this implementations. This is because under this implementations are working Hash Table algorithm and hashcode, equals is required to put values in right bucket. Its important to know that you need to use as keys String or any other wrapper class such us Integer, this is because this objects are immutable and they can be good keys for this implementations or you can create your own immutable class and use it as key. Use immutable objects as key is good practise because after creation they cant change their state hence the hashcode is same always.

Hashtable 是同步的,但 HashMap 不是,但是您可以在方法 Collections.synchronizedMap() 的帮助下使 HashMap 同步。Hashtable、HashMap 和 HashSet 都是基于 Hash Table 数据结构工作的。您可以使用一个空键以及您想要为 HashMap 使用哪种空值,但 Hashtable 不允许空键或空值。基本上在 HashSet 下工作的是 HashMap,其中值是 Object,因此 HashSet 值是唯一的,因为 HashMap 键是唯一的。因此,要将键值对放入 Hashmap 或 Hashtable 或将元素放入 HashSet,您需要从 Object 类中检查 hashcode 和 equals 方法以正确执行此实现。这是因为在此实现下正在使用哈希表算法和哈希码,需要使用 equals 将值放入正确的桶中。重要的是要知道您需要使用 String 或任何其他包装类作为键,例如我们 Integer,这是因为此对象是不可变的,并且它们可以是此实现的好键,或者您可以创建自己的不可变类并将其用作键. 使用不可变对象作为键是一种很好的做法,因为在创建后它们不能改变它们的状态,因此哈希码总是相同的。