Set集合之HashSet

/**

  • Constructs a new, empty set; the backing HashMap instance has

  • the specified initial capacity and default load factor (0.75).

  • @param initialCapacity the initial capacity of the hash table

  • @throws IllegalArgumentException if the initial capacity is less

  •         than zero
    

*/

public HashSet(int initialCapacity) {

map = new HashMap<>(initialCapacity);

}

指定初始化容量的HashSet构造器

内部完成map初始化,初始化容量为指定的初始化容量,但是map底层哈希表实际容量为tableSizeFor(initialCapacity)

public HashSet(int initialCapacity, float loadFactor)


/**

  • Constructs a new, empty set; the backing HashMap instance has

  • the specified initial capacity and the specified load factor.

  • @param initialCapacity the initial capacity of the hash map

  • @param loadFactor the load factor of the hash map

  • @throws IllegalArgumentException if the initial capacity is less

  •         than zero, or if the load factor is nonpositive
    

*/

public HashSet(int initialCapacity, float loadFactor) {

map = new HashMap<>(initialCapacity, loadFactor);

}

指定初始化容量和负载因子的HashSet构造器

内部完成map的初始化,map底层哈希表的初始化容量为tableSizeFor(initialCapacity),负载因子为loadFactor

HashSet(int initialCapacity, float loadFactor, boolean dummy)


/**

  • Constructs a new, empty linked hash set. (This package private

  • constructor is only used by LinkedHashSet.) The backing

  • HashMap instance is a LinkedHashMap with the specified initial

  • capacity and the specified load factor.

  • @param initialCapacity the initial capacity of the hash map

  • @param loadFactor the load factor of the hash map

  • @param dummy ignored (distinguishes this

  •         constructor from other int, float constructor.)
    
  • @throws IllegalArgumentException if the initial capacity is less

  •         than zero, or if the load factor is nonpositive
    

*/

HashSet(int initialCapacity, float loadFactor, boolean dummy) {

map = new LinkedHashMap<>(initialCapacity, loadFactor);

}

该构造器为默认访问权限,即同包访问,即我们日常使用时,无法使用该构造器。

该构造器主要是给HashSet子类LinkedHashSet使用。

成员方法

====

public boolean add(E e)


/**

  • Adds the specified element to this set if it is not already present.

  • More formally, adds the specified element e to this set if

  • this set contains no element e2 such that

  • (enull ? e2null : e.equals(e2)).

  • If this set already contains the element, the call leaves the set

  • unchanged and returns false.

  • @param e element to be added to this set

  • @return true if this set did not already contain the specified

  • element

*/

public boolean add(E e) {

return map.put(e, PRESENT)==null;

}

可以看出HashSet的add方法内部调用HashMap的put方法

HashMap的put方法具有新增和修改功能。其中新增是对于key-valule(返回null),修改是对于value(返回老的value)

而对于HashSet而言,只关注map的key列,value数据永远时PRESENT。所以map的put修改功能对key(HashSet的集合元素)无效果,或者说put修改功能在HashSet体现为永远返回PRESENT。

(注意这里就是为什么将HashSet底层HashMap的value设置为PRESENT,而不是null的原因。如果图方便,将HashSet底层的map的value设置为null,则put重复key时,会导致put方法返回的被覆盖的value值总是null,那么就无法判断HashSet的add方法是否添加key成功了)

所以HashSet新增重复元素时,底层map的key列无变化。此时add方法返回false。

新增不重复元素时,底层map的key会新增元素,此时add方法返回true。

public boolean remove(Object o)


/**

  • Removes the specified element from this set if it is present.

  • More formally, removes an element e such that

  • (onull ? enull : o.equals(e)),

  • if this set contains such an element. Returns true if

  • this set contained the element (or equivalently, if this set

  • changed as a result of the call). (This set will not contain the

  • element once the call returns.)

  • @param o object to be removed from this set, if present

  • @return true if the set contained the specified element

*/

public boolean remove(Object o) {

return map.remove(o)==PRESENT;

}

HashSet的remove方法依赖于底层HashMap的remove方法

我们知道HashMap的remove方法,删除存在的key的键值对时,会将对应的value作为方法返回值,删除不存在的key的键值对时,会直接返回null。

而HashSet底层的HashMap的value永远是PRESENT。所以如果删除的元素(key)存在,则会返回PRESENT,否则返回null。

这就可以帮助HashSet的remove方法判断是否删除成功了。

public void clear()


/**

  • Removes all of the elements from this set.

  • The set will be empty after this call returns.

*/

public void clear() {

map.clear();

}

HashSet的clear方法依赖于底层map的clear方法

public boolean contains(Object o)


/**

  • Returns true if this set contains the specified element.

  • More formally, returns true if and only if this set

  • contains an element e such that

  • (onull ? enull : o.equals(e)).

  • @param o element whose presence in this set is to be tested

  • @return true if this set contains the specified element

*/

public boolean contains(Object o) {

return map.containsKey(o);

}

HashSet的contains方法依赖于底层map的containsKey方法

public int size()


/**

  • Returns the number of elements in this set (its cardinality).

  • @return the number of elements in this set (its cardinality)

*/

public int size() {

return map.size();

}

HashSet的size方法依赖于底层map的size方法

public boolean isEmpty()


/**

  • Returns true if this set contains no elements.

  • @return true if this set contains no elements

*/

public boolean isEmpty() {

return map.isEmpty();

}

HashSet的isEmpty方法依赖于底层map的isEmpty方法

public Object clone()


/**

  • Returns a shallow copy of this HashSet instance: the elements

  • themselves are not cloned.

  • @return a shallow copy of this set

*/

@SuppressWarnings(“unchecked”)

public Object clone() {

try {

HashSet newSet = (HashSet) super.clone();

newSet.map = (HashMap<E, Object>) map.clone();

return newSet;

} catch (CloneNotSupportedException e) {

throw new InternalError(e);

}

}

可以看出HashSet的clone()方法返回的是浅克隆对象,因为没有针对集合元素对象的克隆

迭代器

===

public Iterator iterator()


/**

  • Returns an iterator over the elements in this set. The elements

  • are returned in no particular order.

  • @return an Iterator over the elements in this set

  • @see ConcurrentModificationException

*/

public Iterator iterator() {

return map.keySet().iterator();

}

HashSet的迭代器对象通过iterator()方法返回。

而该方法内部依赖于底层map.keySet().iterator()。map.keySet().iterator()返回的是KeyIterator迭代器对象,该类重写next方法。

而KeyIterator类继承了HashIterator,HashIteator提供了hasNext(),remove()方法

最后

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数初中级Android工程师,想要提升技能,往往是自己摸索成长,自己不成体系的自学效果低效漫长且无助。

因此收集整理了一份《2024年Web前端开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。

img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Android开发知识点!不论你是刚入门Android开发的新手,还是希望在技术上不断提升的资深开发者,这些资料都将为你打开新的学习之门!

如果你觉得这些内容对你有帮助,需要这份全套学习资料的朋友可以戳我获取!!

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!
无助。**

因此收集整理了一份《2024年Web前端开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。

[外链图片转存中…(img-56e4JVH6-1715591199887)]

[外链图片转存中…(img-FjWguA9P-1715591199887)]

[外链图片转存中…(img-6s7LIUAu-1715591199888)]

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Android开发知识点!不论你是刚入门Android开发的新手,还是希望在技术上不断提升的资深开发者,这些资料都将为你打开新的学习之门!

如果你觉得这些内容对你有帮助,需要这份全套学习资料的朋友可以戳我获取!!

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!

### 回答1: HashSetJava中的一种集合类型,它继承自AbstractSet类,并且实现了Set接口。它是基于哈希表实现的,可以存储不重复的元素。HashSet的实现依赖于它存储的元素的hashCode()方法和equals()方法。 当一个元素被添加到HashSet中时,HashSet会首先调用该元素的hashCode()方法,然后根据hashCode()方法的返回值,将该元素放入相应的桶(bucket)中。如果桶中已经存在该元素,则HashSet会调用该元素的equals()方法与桶中的元素进行比较,如果equals()方法返回true,表示这两个元素是相同的,HashSet就不会再次添加该元素。如果equals()方法返回false,则HashSet会将该元素添加到桶中。 由于HashSet是基于哈希表实现的,所以它的查询速度非常快,平均时间复杂度为O(1)。但是,HashSet的迭代顺序并不是按照元素的插入顺序来排列的,而是按照元素的哈希值来排列的。 ### 回答2: HashsetJava集合框架中的一种集合类,它基于哈希表实现,也称为哈希集。与List相比,Hashset集合中的元素不是有序的,而是无序的。而且,Hashset集合中的元素是唯一的,即集合中不存在相同的元素。 哈希表是哈希算法的一种典型应用,Hashset底层通过哈希表来实现。具体来说,当往Hashset中添加元素时,Hashset会先对这个元素进行哈希运算,根据哈希算法得到一个唯一的哈希值。这个哈希值会被作为元素在哈希表中的位置来存储。如果这个位置上已经有其它元素了,那么Hashset会比较这个元素和已存在元素的哈希值和equals()方法,若哈希值相同且equals()方法返回true,则认为这个元素已经存在于集合中,不再添加;否则,哈希表会使用开链的方式在这个位置上存储多个元素。 由于哈希表是一种效率比较高的数据结构,因此Hashset在添加、删除和查找元素时的速度都比较快。但是,由于哈希表的实现依赖于哈希算法的效率,哈希表在存储元素时可能会发生哈希冲突,导致性能下降。通常情况下,为了避免哈希冲突的发生,我们需要根据实际情况来选择合适的哈希函数或者调整哈希表的大小。 总之,Hashset作为Java集合框架中的一种集合类,提供了高效的添加、删除和查找元素的操作,同时也会遇到哈希冲突的问题需要注意。 ### 回答3: Java集合类中的Set是一个不允许有重复元素的集合。而HashSet则是Set接口的一种具体实现,底层实现采用的是哈希表,因此插入、删除和查找的时间复杂度均为O(1)。 HashSet中的元素并没有被排序,因为它是基于哈希表实现的。哈希表通过将元素的关键字映射到数组的索引位置来实现快速访问,即使将大量元素存储在哈希表中,访问元素时仍然能够在常数时间内完成。 HashSet中元素是根据它们的哈希码值存储的,因此先要实现hashCode()方法。此外,还要实现equals()方法来确保HashSet能够正确地判断两个元素是否相等。当两个元素的hashCode()值相等并且equals()方法返回true时,HashSet将认为这两个元素是相同的,不会插入重复元素。 HashSet的迭代器是一种散列码的迭代器,它返回的元素不会保证按照任何特定的顺序排列。当遍历HashSet时,不能保证元素的迭代顺序与元素插入的顺序相同。 在使用HashSet时需要注意,由于哈希表的实现,HashSet不是线程安全的,如果多个线程同时访问HashSet,可能会导致意外的结果,需要进行同步处理。 总之,HashSet是一个高效的集合实现,它允许快速的插入、删除和查找。如果你需要一个不允许重复元素的无序集合,并且希望能够快速地访问和修改元素,那么HashSet是一个不错的选择。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值