java中的hashset_Java中的HashSet
java中的hashset
介紹:
Java中的HashSet實(shí)現(xiàn)Set接口,即它不允許重復(fù)。 它在內(nèi)部由HashMap支持,該哈希表基于哈希原理。
我們可以在HashSet中存儲(chǔ)一個(gè)空值。 默認(rèn)容量為16,負(fù)載系數(shù)為0.75,其中:
Load factor = Number of Stored Elements / capacityJava HashSet是不同步的。 同樣,不能保證保留元素的插入順序。
在本教程中,我們將學(xué)習(xí)如何使用Java HashSet 。
實(shí)例化
我們可以使用以下構(gòu)造函數(shù)之一創(chuàng)建Java HashSet :
HashSet() // default capacity of 16 with a load factor of 0.75 HashSet(int initialCapacity) HashSet(int initialCapacity, float loadFactor) HashSet(Collection c)這些構(gòu)造函數(shù)的用法都很直觀。
讓我們使用默認(rèn)構(gòu)造函數(shù)快速創(chuàng)建一個(gè)HashSet:
Set<Integer> set = new HashSet<>();常用方法:
現(xiàn)在讓我們看一些可以幫助我們操縱Java HashSet的方法:
1.
它只是將元素添加到給定的集合(如果尚不存在)。 如果該元素已經(jīng)存在,則add()僅返回false:
System.out.println(set.add(1)); //true System.out.println(set.add(2)); //true System.out.println(set.add(3)); //true System.out.println(set.add(1)); //false - as already present//Note that the order of elements isn't guaranteed System.out.println(set); //[1, 2, 3]2.
如果元素在引用集中存在,則contains()方法返回true ,否則返回false :
System.out.println(set.contains(1)); //true System.out.println(set.contains(4)); //false3.
顧名思義,它將刪除元素obj(如果存在)并返回true 。 如果不存在這樣的元素,則僅返回false :
System.out.println(set.remove(1)); //true System.out.println(set.remove(4)); //false請(qǐng)注意, HashSet還繼承了removeAll()和removeIf()方法,可用于刪除值。
4.
對(duì)于空集返回true ,否則返回false :
System.out.println(set.isEmpty()); // false5. int
它僅返回給定集中存在的元素?cái)?shù)。
6.
clear()方法刪除引用集中存在的所有值,從而使其成為空集。
內(nèi)部實(shí)施:
HashSet在內(nèi)部使用HashMap來(lái)存儲(chǔ)其元素。 存儲(chǔ)在HashSet中的元素被映射為HashMap中的鍵。 所有這些條目的值字段都包含一個(gè)常量PRESENT:
private static final Object PRESENT = new Object();這是一個(gè)虛擬對(duì)象。
遍歷
我們可以使用以下一種方式來(lái)迭代HashSet中的元素:
1.
從Java 8開始,我們可以使用forEach()遍歷任何Java 集合:
set.forEach(e -> System.out.println(e));2.
Java 8還支持forEachRemaining()構(gòu)造,該構(gòu)造可與Collection上的任何迭代器一起使用:
Iterator<Integer> itr = set.iterator();itr.forEachRemaining(e -> System.out.println(e));3.使用
如果我們使用的是Java 7或更低版??本,我們可以簡(jiǎn)單地使用迭代器進(jìn)行迭代:
Iterator<Integer> itr = set.iterator();while(itr.hasNext()) {System.out.println(itr.next()); }4.擴(kuò)展
我們還可以使用擴(kuò)展的for循環(huán)遍歷元素:
for(Integer e : set) {System.out.println(e); }結(jié)論:
在本教程中,我們學(xué)習(xí)了如何創(chuàng)建和使用Java HashSet。 我們也知道Java HashSet在內(nèi)部使用HashMap來(lái)實(shí)現(xiàn)它。
成為第一個(gè)發(fā)表評(píng)論的人。
翻譯自: https://www.javacodegeeks.com/2019/04/hashset-java.html
java中的hashset
總結(jié)
以上是生活随笔為你收集整理的java中的hashset_Java中的HashSet的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 错误代码404怎么处理(错误代码404怎
- 下一篇: java uuid_Java UUID