java中的hashset_Java中的HashSet
java中的hashset
介紹:
Java中的HashSet實現Set接口,即它不允許重復。 它在內部由HashMap支持,該哈希表基于哈希原理。
我們可以在HashSet中存儲一個空值。 默認容量為16,負載系數為0.75,其中:
Load factor = Number of Stored Elements / capacityJava HashSet是不同步的。 同樣,不能保證保留元素的插入順序。
在本教程中,我們將學習如何使用Java HashSet 。
實例化
我們可以使用以下構造函數之一創建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)這些構造函數的用法都很直觀。
讓我們使用默認構造函數快速創建一個HashSet:
Set<Integer> set = new HashSet<>();常用方法:
現在讓我們看一些可以幫助我們操縱Java HashSet的方法:
1.
它只是將元素添加到給定的集合(如果尚不存在)。 如果該元素已經存在,則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請注意, HashSet還繼承了removeAll()和removeIf()方法,可用于刪除值。
4.
對于空集返回true ,否則返回false :
System.out.println(set.isEmpty()); // false5. int
它僅返回給定集中存在的元素數。
6.
clear()方法刪除引用集中存在的所有值,從而使其成為空集。
內部實施:
HashSet在內部使用HashMap來存儲其元素。 存儲在HashSet中的元素被映射為HashMap中的鍵。 所有這些條目的值字段都包含一個常量PRESENT:
private static final Object PRESENT = new Object();這是一個虛擬對象。
遍歷
我們可以使用以下一種方式來迭代HashSet中的元素:
1.
從Java 8開始,我們可以使用forEach()遍歷任何Java 集合:
set.forEach(e -> System.out.println(e));2.
Java 8還支持forEachRemaining()構造,該構造可與Collection上的任何迭代器一起使用:
Iterator<Integer> itr = set.iterator();itr.forEachRemaining(e -> System.out.println(e));3.使用
如果我們使用的是Java 7或更低版??本,我們可以簡單地使用迭代器進行迭代:
Iterator<Integer> itr = set.iterator();while(itr.hasNext()) {System.out.println(itr.next()); }4.擴展
我們還可以使用擴展的for循環遍歷元素:
for(Integer e : set) {System.out.println(e); }結論:
在本教程中,我們學習了如何創建和使用Java HashSet。 我們也知道Java HashSet在內部使用HashMap來實現它。
成為第一個發表評論的人。
翻譯自: https://www.javacodegeeks.com/2019/04/hashset-java.html
java中的hashset
總結
以上是生活随笔為你收集整理的java中的hashset_Java中的HashSet的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 错误代码404怎么处理(错误代码404怎
- 下一篇: 怎么修改404页面(怎么修改404页面密