JDK8 HashSet源码解析

HashSet源码解析(基于JDK1.8) HashSet是Java中经常被用到的集合,弄清它的底层实现,有利于我们更好地使用它,又是这句话….. 不过HashSet相对于其他集合框架简单了不少。 老规矩,还是先看看它的UML图: ①:实现了Serializable接口,表明它支持序列化。 ②:实现了Cloneable接口,表明它支持克隆,可以调用超类的clone()方法进行浅拷贝。 ③继承了AbstractSet抽象类... 阅读详情

前言

HashSet我们使用很多,但仅仅在使用的角度,用法很简单,现在分析原理

1. 总体概览

public class HashSet<E>
    extends AbstractSet<E>
    implements Set<E>, Cloneable, java.io.Serializable
{
    static final long serialVersionUID = -5024744406713321676L;

    private transient HashMap<E,Object> map;

    // Dummy value to associate with an Object in the backing Map
    private static final Object PRESENT = new Object();

可以看出HashSet的本质就是HashMap,transient 修饰,使用自定义序列化

map的key就是存储的元素E,value是同一个对象final Object PRESENT

1.1 分析自定义序列化

    /**
     * Save the state of this <tt>HashSet</tt> instance to a stream (that is,
     * serialize it).
     *
     * @serialData The capacity of the backing <tt>HashMap</tt> instance
     *             (int), and its load factor (float) are emitted, followed by
     *             the size of the set (the number of elements it contains)
     *             (int), followed by all of its elements (each an Object) in
     *             no particular order.
     */
    private void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException {
        // Write out any hidden serialization magic
        s.defaultWriteObject();

        // Write out HashMap capacity and load factor
        s.writeInt(map.capacity());
        s.writeFloat(map.loadFactor());

        // Write out size
        s.writeInt(map.size());

        // Write out all elements in the proper order.
        //map的每一个元素,实现深度克隆
        for (E e : map.keySet())
            s.writeObject(e);
    }

    /**
     * Reconstitute the <tt>HashSet</tt> instance from a stream (that is,
     * deserialize it).
     */
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
        // Read in any hidden serialization magic
        s.defaultReadObject();

        // Read capacity and verify non-negative.
        int capacity = s.readInt();
        if (capacity < 0) {
            throw new InvalidObjectException("Illegal capacity: " +
                                             capacity);
        }

        // Read load factor and verify positive and non NaN.
        float loadFactor = s.readFloat();
        if (loadFactor <= 0 || Float.isNaN(loadFactor)) {
            throw new InvalidObjectException("Illegal load factor: " +
                                             loadFactor);
        }

        // Read size and verify non-negative.
        int size = s.readInt();
        if (size < 0) {
            throw new InvalidObjectException("Illegal size: " +
                                             size);
        }
        // Set the capacity according to the size and load factor ensuring that
        // the HashMap is at least 25% full but clamping to maximum capacity.
        capacity = (int) Math.min(size * Math.min(1 / loadFactor, 4.0f),
                HashMap.MAXIMUM_CAPACITY);

        // Constructing the backing map will lazily create an array when the first element is
        // added, so check it before construction. Call HashMap.tableSizeFor to compute the
        // actual allocation size. Check Map.Entry[].class since it's the nearest public type to
        // what is actually created.

        SharedSecrets.getJavaOISAccess()
                     .checkArray(s, Map.Entry[].class, HashMap.tableSizeFor(capacity));

        // Create backing HashMap
        map = (((HashSet<?>)this) instanceof LinkedHashSet ?
               new LinkedHashMap<E,Object>(capacity, loadFactor) :
               new HashMap<E,Object>(capacity, loadFactor));

        // Read in all elements in the proper order.
        //map的每一个元素读取
        for (int i=0; i<size; i++) {
            @SuppressWarnings("unchecked")
                E e = (E) s.readObject();
            map.put(e, PRESENT);
        }
    }

1.2 覆写克隆方法

    /**
     * Returns a shallow copy of this <tt>HashSet</tt> instance: the elements
     * themselves are not cloned.
     *
     * @return a shallow copy of this set
     */
    @SuppressWarnings("unchecked")
    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(e);
        }
    }

同时克隆set和map属性。

2. 构造函数

    /**
     * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
     * default initial capacity (16) and load factor (0.75).
     */
    public HashSet() {
        map = new HashMap<>();
    }

    /**
     * Constructs a new set containing the elements in the specified
     * collection.  The <tt>HashMap</tt> is created with default load factor
     * (0.75) and an initial capacity sufficient to contain the elements in
     * the specified collection.
     *
     * @param c the collection whose elements are to be placed into this set
     * @throws NullPointerException if the specified collection is null
     */
    public HashSet(Collection<? extends E> c) {
        map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16));
        addAll(c);
    }
 

    /**
     * Constructs a new, empty set; the backing <tt>HashMap</tt> 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);
    }

    /**
     * Constructs a new, empty set; the backing <tt>HashMap</tt> 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);
    }

    /**
     * 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);
    }

addAll方法 

public abstract class AbstractCollection<E> implements Collection<E> {
    public boolean addAll(Collection<? extends E> c) {
        boolean modified = false;
        for (E e : c)
            if (add(e))
                modified = true;
        return modified;
    }

 直接使用HashMap构造

3. 关键方法分析

3.1 add方法

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

map塞值。

3.2 remove方法

    public boolean remove(Object o) {
        return map.remove(o)==PRESENT;
    }

map的remove

3.3 contains方法

    public boolean contains(Object o) {
        return map.containsKey(o);
    }

4. 总结

Set的本质就是Map。Map的key就是Set的元素,value为同一个Object对象。非常简单。

HashSet中add解析 本文章基于JDK1.8 上代码 final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) { Node<K,V>[] tab; Node<K,V> p; int n, i; //table为空或者tab的长度为0,进行初始化操作 if ((tab = table) == null || (n = 阅读详情

相关推荐

4D毫米波雷达点云可视化实战:从CANFD原始数据到Matplotlib三维动态图

本文详细介绍了4D毫米波雷达点云可视化实战,从CANFD原始数据解析到Matplotlib三维动态图实现的全流程。通过解析CANFD数据帧结构、点云数据编码原理,并结合Python实现CANFD通信接口,帮助开发者掌握4D雷达数据处理与优化技巧,最终实现高性能的3D点云动态可视化。

u9v0w的博客 568

Java HashSet源码分析(JDK8)

HashSet的底层是由HashMap实现的,用了HashMap的key来存储元素,value为默认的对象,因HashMap的key是不能够重复的所以也就造成了HashSet集合元素的不可重复性。

coding is an art 1727

详细解读文字识别工具———Tesseract-OCR

   在尝试破解12306验证码的时候,提前了解了一下应对各种验证码的解决方案,这里主要是学习到了面对文字图片验证码,例如亚马逊、豆瓣等平台的登录时会遇到的情况,效果还不错。 一、工具介绍 ​    Tesseract-OCR 是一款由HP实验室开发由Google维护的开源OCR(Optical Character Recognition...

别看我只是一只羊 2万+

JDK 8 HashSet 详解及详细源码展示

JDK 8中的HashSet是基于HashMap实现的无序集合,内部使用HashMap存储元素(元素作为键,固定对象PRESENT作为值)。它提供O(1)时间复杂度的增删查操作,通过equals()和hashCode()保证元素唯一性。HashSet不保证迭代顺序,非线程安全,适合去重和快速查找场景。使用时需注意哈希码稳定性、线程安全等问题,有序需求可改用LinkedHashSet。核心优势在于利用HashMap实现高效集合操作,理解其底层实现有助于正确使用。

csdn_tom_168的博客 1127

Android蓝牙Mesh组网实战:从零搭建智能灯光控制系统(附完整代码)

本文详细介绍了基于Android平台开发蓝牙Mesh智能灯光控制系统的完整实战流程。从环境搭建、核心概念解析,到设备扫描配网、网络初始化、模型配置与消息通信,提供了完整的代码实现和调试技巧。重点讲解了如何使用开源Mesh库实现设备发现、分组控制、场景管理等核心功能,并分享了实际项目中遇到的典型问题与解决方案。

weixin_29174013的博客 656

2025软考中级《数据库系统工程师》案例模拟题合集

1.【说明】某销售企业正在实施电商平台项目,主要功能模块包括用户中心、商品中心、交易中心、支付中心、营销中心等。其中支付中心模块包括了一个账户表:Account (ano, aname, balance),其中属性含义分别为:账户号,账户名称和账户余额。 假设现在存在事务Ti对账户表Account进行余额的修改,系统记录了修改账户表的日志记录,假设更新日志记录表示为 <Ti,A,V1,V2>,表明事务Ti对账户A执行了一个写操作,写操作前账户A的余额是V1,写操作后账户A的余额为V2。<Ti,D

2301_76902257的博客 2328

JAVA集合篇之HashSet底层源码(JDK8)

/至此,添加重复元素的逻辑处理结束,这里再分析一下再数组表中已经存在元素的时候的扩容机制resize(),分析见蓝色注释。// 将e指向p的下一个结点(p.next),判断p的下一个结点是否为null。else { // 计算出来的位置相同,但判断不是相同对象,也不是树结点,会进入该分支。//因此,当添加的元素已经有8个,继续添加的时候满足该if条件。// 因此,还要数组大小

qq_35099823的博客 2156

开源数显表

开源数显表,广泛应用于车床、铣床、磨床、镗床、火花机、线切割等。市面上此类液晶数显表多数都是基于此项目。 一、基本配置 硬件 主控:STM32F407VGT6 LCD:群创AT070TN92 显示驱动:RA8875 光栅尺:3 x 输入(X/Y/Z) 串口:1 x MAX3232 继电器:2 x 输出 存储:AT24C64 模拟输入:LM324C 电源:AC 220V 软件 工程版本:Keil 5 STM32库:V1.4.0 图形界面:uCGUI 多语言支持:中文、英文 二、项目文

m0_70934529的博客 435

JAVA集合之HashSet源码解析(JDK8)

文章目录前言源码解析HashSet类HashSet属性HashSet构造器HashSet主要方法总结 前言         我们在实际项目中通常会有这样的需求,将多个数据存储在一起,但是不希望得到重复的数据,那么HashSet将可以满足去重。 源码解析 HashSet类 HashSet是一个继承于AbstractSet...

qq_18581221的博客 3539

视觉测量实战:C#上位机+OpenCVSharp 实现工业零件尺寸自动检测(精准像素级,工业级可落地)

本次开发的上位机界面遵循工业现场操作规范简洁、直观、按钮大、文字清晰、参数可视化调节,操作人员为车间工人/质检员,无需复杂操作,所有控件均为WinForms原生控件,拖拽即可完成布局本次实战完成了C#上位机+OpenCVSharp 工业零件尺寸自动检测系统的完整开发,这套方案是工业视觉测量的标准落地方案,适配95%的规则几何零件的尺寸检测场景,从五金件、塑胶件到电子元件,全覆盖无死角。测量效率提升100倍、精度提升10倍、无人工误差、可适配流水线实时检测。

这里只有干货:从 Modbus 通信到 MES 对接,从 YOLO 训练到工控机部署,带你搞定工业软件开发全流程。 849

[Bug已解决] CUDA error 尽管 CUDA 可用且 GPU 受支持-通用排查 RuntimeError 解决方案

[Bug已解决] CUDA error 尽管 CUDA 可用且 GPU 受支持-通用排查 RuntimeError 解决方案

一键难忘的博客 2415

JDK 8 HashSet 源码解析

【本文是为了梳理知识的总结性文章,总结了一些自认为相关的重要知识点,只为巩固记忆以及技术交流,忘批评指正。其中参考了很多前辈的文章,包括图片也是引用,如有冒犯,侵删。】 0存储结构 从底层实现来看,HashSet调用了HashMap来存储元素,不过之用到了Key,Value则用一个固定对象替代。由于Map中的key是不可重复的,这和Set不存在重复元素的特点刚好契合。使用HashMap也意...

InkGenius 508

pytest学习和使用19-pytest断言失败后,怎样保持后续的断言继续执行?(pytest-assume)

【代码】pytest学习和使用19-pytes断言失败后,怎样保持后续的断言继续执行?

虫无涯的博客 1390

HashSet源码解析(JDK1.8)

HashSet源码解析(JDK1.8) 文章目录HashSet源码解析(JDK1.8)HashSet实现原理HashSet的属性HashSet的方法构造方法空参构造HashSet()HashSet(Collection<? extends E> c)HashSet(int initialCapacity, float loadFactor)HashSet(int initialCapacity)HashSet(int initialCapacity, float loadFactor, bool

qq_44709990的博客 955

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

HashSet源码解析——基于JDK1.8

前言 HashSet 是一个不允许存储重复元素的集合,它的实现比较简单,只要理解了 HashMap,HashSet 就水到渠成了。当然了解HashMap可以参考我的这篇文章 1 常量介绍 //使用HashMap来实现Set的相关功能 private transient HashMap<E,Object> map; // 将假value与map中的对象关联 // Dumm...

nero_claudius的博客 268

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

HashSet源码解析 --基于JDK1.8

文章目录结构属性构造器方法add: 结构 public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, java.io.Serializable { } HashSet继承自AbstractSet,实现了Set, Cloneable, java.io.Serializable接口。 属性 //序列化id static final long serialV

qq_41202539的博客 457

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

HashSet源码解析(JDK1.8)

在我们学过HashMap之后,再来看HashSet就很easy了。因为HashSet是基于HashMap是实现的。打开HashSet的源码,可以看到维护了一个HashMap一、成员变量//用来存储HashSet的元素 private transient HashMap&lt;E,Object&gt; map; //这个Object是用来填充HashMap的value的。 private stati...

yanghan1222的博客 195

HashSet、CopyOnWriteArraySet、ConcurrentSkipListSet源码解析(JDK1.8)

set源码解析HashSet源码解析HashSet简单使用的demoHashSet中的变量合理的创建标题,有助于目录的生成如何改变文本的样式插入链接与图片如何插入一段漂亮的代码片生成一个适合你的列表创建一个表格设定内容居中、居左、居右SmartyPants创建一个自定义列表如何创建一个注脚注释也是必不可少的KaTeX数学公式新的甘特图功能,丰富你的文章UML 图表FLowchart流程图导出与导入...

狐言 358

JAVA集合源码解析 HashSet 探索(基于JDK1.8)

JDK1.8HashSet探索 本文所讨论的源码是基于JDK1.8展开的,由于篇幅有限,只讨论主要部分 JDK1.8HashSet探索 1.简介 2.探索 2.1类关系 2.2属性 2.3构造方法 2.4核心方法 3.总结 1.简介 HashSet 是不同步的,继承的 set 接口,所以里面的元素是不能重复的,无序的,允许包含值为null的元素,但最多只能有...

我在阴山下 666

JDK8集合类源码解析 - HashSet

HashSet 特点:不允许放入重复元素 查看源码,发现HashSet是基于HashMap来实现的,对HashMap做了一次“封装”。 private transient HashMap<E,Object> map; private static final Object PRESENT = new Object(); //map的value ...

weixin_30752377的博客 94

Java集合深入学习 - HashSet源码解析(基于jdk1.8)

HashSet。。。感觉就像是一个阉割版的HashMap。。 /** * 定义HashSet类 继承 AbstractSet 实现Set,Cloneable,Serializable */ public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, java.io.Serializable { static final long serialVersionUID

luo_mu_hpu的博客 199

HashSet

HashSet源码解析(基于JDK1.8)_m0_37884977的博客-优快云博客_hashset源码

pubgNO1的博客 366

JDK1.8源码阅读记录HashSet类

JDK1.8源码阅读记录 JAVA.Util包 HashSet类 说明 public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, java.io.Serializable HashSet类继承了AbstractSet抽象类,实现了Set、Clonea...

weixin_43459704的博客 173

JDK 8 HashSet 源码详解(完整版带详细注释)

JDK 8 的 HashSet 是基于 HashMap 实现的集合类,所有元素作为 HashMap 的 key 存储,对应的 value 统一使用 PRESENT 对象占位。核心特性包括:默认初始容量 16,负载因子 0.75;通过 HashMap 实现基本操作(add/remove/contains 时间复杂度 O(1));支持序列化和克隆;迭代器返回元素的顺序无序。LinkedHashSet 继承 HashSet,通过 LinkedHashMap 保持插入顺序。源码实现包含构造方法、核心操作方法(add

csdn_tom_168的博客 659

Java CopyOnWriteArraySet源码深度解析

介绍了JDK1.8的CopyOnWriteArraySet的特性和源码实现!

终生学习践行者 2348
上一篇: 线程的实现,调度和生命周期
下一篇: JDK8线程池-Executors-ThreadPoolExecutor用法
fenglllle
博客等级 码龄8年 461粉丝 242原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值