除了HashSet不允许重复值之外,HashMap和HashSet之间还有什么区别呢?

我是说执行方面?这有点模糊,因为两者都使用哈希表来存储值。


当前回答

Hashset内部实现HashMap。如果您看到内部实现,则HashSet中插入的值将存储为HashMap中的键,并且该值是object类的Dummy对象。 HashMap和HashSet的区别是:-

HashMap contains key value pairs and each value can be accessed by key where as HashSet needs to be iterated everytime as there is no get method. HashMap implements Map interface and allows one null value as a key and multiple null values as values, whereas HashSet implements Set interface, allows only one null value and no duplicated values.(Remeber one null key is allowed in HashMap key hence one null value in HashSet as HashSet implemements HashMap internally). HashSet and HashMap do not maintain the order of insertion while iterating.

其他回答

HashSet允许我们在集合中存储对象,而HashMap允许我们在键和值的基础上存储对象。每个对象或存储对象都有键。

基本上在HashMap中,用户必须同时提供Key和Value,而在HashSet中只提供Value, Key是通过哈希函数从Value自动派生出来的。因此,在拥有Key和Value之后,HashSet可以在内部存储为HashMap。

HashSet和HashMap都是存储对,区别在于在HashMap中你可以指定一个键,而在HashSet中键来自对象的哈希代码

Java中HashSet和HashMap的区别

1) HashMap和HashSet之间的第一个也是最重要的区别是HashMap是Map接口的实现,而HashSet是Set接口的实现,这意味着HashMap是一个基于键值的数据结构,HashSet通过不允许重复来保证唯一性。在现实中,HashSet是Java中HashMap的包装器,如果你看一下HashSet. Java的add(E E)方法的代码,你会看到以下代码:

public boolean add(E e) 
{
    return map.put(e, PRESENT)==null;
}

其中,它将Object放入map中作为键和值,是一个最终对象PRESENT,它是dummy。

2) HashMap和HashSet的第二个区别是,我们使用add()方法将元素放入Set,但我们使用put()方法在Java中将键和值插入HashMap。

3) HashSet只允许一个空键,而HashMap可以允许一个空键+多个空值。

以上就是Java中HashSet和HashMap的区别。总之,HashSet和HashMap是两种不同类型的集合,一个是Set,另一个是Map。

Hashset内部实现HashMap。如果您看到内部实现,则HashSet中插入的值将存储为HashMap中的键,并且该值是object类的Dummy对象。 HashMap和HashSet的区别是:-

HashMap contains key value pairs and each value can be accessed by key where as HashSet needs to be iterated everytime as there is no get method. HashMap implements Map interface and allows one null value as a key and multiple null values as values, whereas HashSet implements Set interface, allows only one null value and no duplicated values.(Remeber one null key is allowed in HashMap key hence one null value in HashSet as HashSet implemements HashMap internally). HashSet and HashMap do not maintain the order of insertion while iterating.