Java Improvement (24) -----HashSet
Original text from: http://www.php.cn/
## In the previous blog post (java Improvement Chapter (23) -----HashMap) explains the implementation process of HashMap in detail. For HashSet, it is implemented based on HashMap, and the bottom layer uses HashMap to save elements. So if you are familiar with HashMap, then HashSet is so easy!!
1. Definition
public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, java.io.Serializable
HashSet inherits the AbstractSet class and implements the Set, Cloneable, and Serializable interfaces. Among them, AbstractSet provides the backbone implementation of the Set interface, thus minimizing the work required to implement this interface. The Set interface is a Collection that does not contain duplicate elements. It maintains its own internal ordering, so random access does not make sense.
Basic attributes
//基于HashMap实现,底层使用HashMap保存所有元素 private transient HashMap<E,Object> map; //定义一个Object对象作为HashMap的value private static final Object PRESENT = new Object();
## Constructor
/** * 默认构造函数 * 初始化一个空的HashMap,并使用默认初始容量为16和加载因子0.75。 */ public HashSet() { map = new HashMap<>(); } /** * 构造一个包含指定 collection 中的元素的新 set。 */ public HashSet(Collection<? extends E> c) { map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16)); addAll(c); } /** * 构造一个新的空 set,其底层 HashMap 实例具有指定的初始容量和指定的加载因子 */ public HashSet(int initialCapacity, float loadFactor) { map = new HashMap<>(initialCapacity, loadFactor); } /** * 构造一个新的空 set,其底层 HashMap 实例具有指定的初始容量和默认的加载因子(0.75)。 */ public HashSet(int initialCapacity) { map = new HashMap<>(initialCapacity); } /** * 在API中我没有看到这个构造函数,今天看源码才发现(原来访问权限为包权限,不对外公开的) * 以指定的initialCapacity和loadFactor构造一个新的空链接哈希集合。 * dummy 为标识 该构造函数主要作用是对LinkedHashSet起到一个支持作用 */ HashSet(int initialCapacity, float loadFactor, boolean dummy) { map = new LinkedHashMap<>(initialCapacity, loadFactor); }
2. Method
Since HashSet is based on HashMap, then for HashSet, the implementation process of its method is very simple.
public Iterator<E> iterator() { return map.keySet().iterator(); }
The iterator() method returns an iterator that iterates over the elements in this set. The order in which the elements are returned is not specific. The underlying call to HashMap's keySet returns all keys. This reflects that all elements in the HashSet are stored in the HashMap's key, and the value is the PRESENT object used, which is static final.
public int size() { return map.size(); }
size() returns the number of elements in this set (the capacity of the set). The bottom layer calls the size method of HashMap and returns the size of the HashMap container.
public boolean isEmpty() { return map.isEmpty(); }
isEmpty(), determines whether the HashSet() collection is empty, and returns if it is empty true, otherwise false
is returned.public boolean contains(Object o) {
return map.containsKey(o);
}
#contains(), determines whether an element exists in HashSet(), returns true if it exists , otherwise return false. To be more precise, this relationship should be satisfied to return true: (o==null ? e==null : o.equals(e)). The bottom layer calls containsKey to determine whether the key value of HashMap is empty.
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
add() If this set does not yet contain the specified element, add the specified element. If this Set does not contain e2 that satisfies (e==null ? e2==null : e.equals(e2)), then e2 is added to the Set, otherwise it is not added and false is returned. Since the bottom layer uses the put method of HashMap to construct key = e, value = PRESENT into a key-value pair, when e exists in the key of HashMap, the value will overwrite the original value, but the key remains unchanged, so If an existing e element is added to the HashSet, the newly added element will not be saved in the HashMap, so this satisfies the feature that the elements in the HashSet will not be repeated.
public boolean remove(Object o) {
return map.remove(o)==PRESENT;
}
removeIf the specified element exists in this set, remove it. The bottom layer uses the remove method of HashMap to delete the specified Entry.
public void clear() { map.clear(); }
clear从此 set 中移除所有元素。底层调用HashMap的clear方法清除所有的Entry。
public Object clone() { try { HashSet<E> newSet = (HashSet<E>) super.clone(); newSet.map = (HashMap<E, Object>) map.clone(); return newSet; } catch (CloneNotSupportedException e) { throw new InternalError(); } }
clone返回此 HashSet 实例的浅表副本:并没有复制这些元素本身。
后记:
由于HashSet底层使用了HashMap实现,使其的实现过程变得非常简单,如果你对HashMap比较了解,那么HashSet简直是小菜一碟。有两个方法对HashMap和HashSet而言是非常重要的,下篇将详细讲解hashcode和equals。
---------------------------------------------------------------------------------------------------------
以上就是java提高篇(二四)-----HashSet的内容,更多相关内容请关注PHP中文网(www.php.cn)!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo
