ArrayList源码分析

Java集合源码剖析 Java集合源码剖析 ArrayList 底层结构:ArrayList 类是一个可以动态修改的数组,与普通数组的区别就是它是没有固定大小的限制,我们可以添加或删除元素(动态数组)。 ArrayList底层是数组,允许元素是null,能够动态扩容 size、isEmpty、get、set、add 等方法时间复杂度都是 O (1) 非线程安全,并发修改时,会抛出ConcurrentModificationException 初始化 ArrayList<E> 阅读详情

成员变量

 private transient Object[] elementData;
ArrayList内部实现的数组变量

private int size;
ArrayList包含的元素个数

构造函数部分

public ArrayList(int initialCapacity) {
	super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
	this.elementData = new Object[initialCapacity];
    }

    /**
     * Constructs an empty list with an initial capacity of ten.
     */
    public ArrayList() {
	this(10);
    }

    /**
     * Constructs a list containing the elements of the specified
     * collection, in the order they are returned by the collection's
     * iterator.
     *
     * @param c the collection whose elements are to be placed into this list
     * @throws NullPointerException if the specified collection is null
     */
    public ArrayList(Collection<? extends E> c) {
	elementData = c.toArray();
	size = elementData.length;
	// c.toArray might (incorrectly) not return Object[] (see 6260652)
	if (elementData.getClass() != Object[].class)
	    elementData = Arrays.copyOf(elementData, size, Object[].class);
    }
在构造ArrayList的时候可以指定大小,如果没有指定该参数默认大小为10。

对于集合参数的那个构造有这样一段代码

// c.toArray might (incorrectly) not return Object[] (see 6260652)
	if (elementData.getClass() != Object[].class)
	    elementData = Arrays.copyOf(elementData, size, Object[].class);

第一眼看到觉得很奇怪,java中有谁不是Object的子类?搜索了一下,原来这是一个bug, 详细说明见此。测试代码如下:

public static void main(String[] args) {
		List l = Arrays.asList(new String[]{"a", "b"});
	    System.out.println(l.toArray().getClass());
	    System.out.println(l.toArray(new Object[0]).getClass());
	}
输出结果:

class [Ljava.lang.String;
class [Ljava.lang.Object;

部分方法分析

trimToSize

public void trimToSize() {
	modCount++;
	int oldCapacity = elementData.length;
	if (size < oldCapacity) {
            elementData = Arrays.copyOf(elementData, size);
	}
    }
由于elementData的长度会被拓展,size标记的是其中包含的元素的个数。所以会出现size很小但elementData.length很大 的情况,将出现空间的浪费。trimToSize将返回一个新的数组给elementData,元素内容保持不变,length很size相同,节省空间。可在内存不足时使用。

ensureCapacity

 public void ensureCapacity(int minCapacity) {
	modCount++;
	int oldCapacity = elementData.length;
	if (minCapacity > oldCapacity) {
	    Object oldData[] = elementData;
	    int newCapacity = (oldCapacity * 3)/2 + 1;
    	    if (newCapacity < minCapacity)
		newCapacity = minCapacity;
            // minCapacity is usually close to size, so this is a win:
            elementData = Arrays.copyOf(elementData, newCapacity);
	}
    }
该方法主要用于扩充数组大小,可以看出当满足扩容条件时每次扩容后数组的大小至少是之前的1.5倍+1

indexOf

 public int indexOf(Object o) {
	if (o == null) {
	    for (int i = 0; i < size; i++)
		if (elementData[i]==null)
		    return i;
	} else {
	    for (int i = 0; i < size; i++)
		if (o.equals(elementData[i]))
		    return i;
	}
	return -1;
    }
返回第一次出现某个元素的下标,未找到返回-1

lastIndexOf

 public int lastIndexOf(Object o) {
	if (o == null) {
	    for (int i = size-1; i >= 0; i--)
		if (elementData[i]==null)
		    return i;
	} else {
	    for (int i = size-1; i >= 0; i--)
		if (o.equals(elementData[i]))
		    return i;
	}
	return -1;
    }
返回最后一次出现某个元素的下标,未找到返回-1

clone

 public Object clone() {
	try {
	    ArrayList<E> v = (ArrayList<E>) super.clone();
	    v.elementData = Arrays.copyOf(elementData, size);
	    v.modCount = 0;
	    return v;
	} catch (CloneNotSupportedException e) {
	    // this shouldn't happen, since we are Cloneable
	    throw new InternalError();
	}
    }

覆写clone方法

toArray

public Object[] toArray() {
        return Arrays.copyOf(elementData, size);
    }
返回数组。注意返回的是新new的一个数组,那么你对这个返回的数组所执行的任何操作都不至于会影响到该ArrayList内部实现的数组。

public <T> T[] toArray(T[] a) {
        if (a.length < size)
            // Make a new array of a's runtime type, but my contents:
            return (T[]) Arrays.copyOf(elementData, size, a.getClass());
	System.arraycopy(elementData, 0, a, 0, size);
          if (a.length > size)
            a[size] = null;
	return a; }
首先判断传入的数组大小不能不够情况直接返回一个类型为T的新数组,当大小足够的情况下会将当前list中的元素拷贝之出入的数组中[0,size)的位置,但是之后的这个语句是什么意思呢?
 if (a.length > size)
            a[size] = null;
为什么要在大小大于size的情况下将a[size]设置为null?不懂就google吧。在csdn上找到这篇 帖子,意思说是分界用的。

add

 public boolean add(E e) {
	ensureCapacity(size + 1);  // Increments modCount!!
	elementData[size++] = e;
	return true;
    }

可以看出add方法每次在调用的时候都会调用扩容方法ensureCapacity,由此可见在构造ArrayList的时候设置大小很有作用,否则add每次扩容很消耗新能。

  public void add(int index, E element) {
	if (index > size || index < 0)
	    throw new IndexOutOfBoundsException(
		"Index: "+index+", Size: "+size);

	ensureCapacity(size+1);  // Increments modCount!!
	System.arraycopy(elementData, index, elementData, index + 1,
			 size - index);
	elementData[index] = element;
	size++;
    }
在指定位置插入元素

remove

 public E remove(int index) {
	RangeCheck(index);

	modCount++;
	E oldValue = (E) elementData[index];

	int numMoved = size - index - 1;
	if (numMoved > 0)
	    System.arraycopy(elementData, index+1, elementData, index,
			     numMoved);
	elementData[--size] = null; // Let gc do its work

	return oldValue;
    }
通过下标删除元素,如果删除的不是最后一个元素会执行数组拷贝操作。

public boolean remove(Object o) {
	if (o == null) {
            for (int index = 0; index < size; index++)
		if (elementData[index] == null) {
		    fastRemove(index);
		    return true;
		}
	} else {
	    for (int index = 0; index < size; index++)
		if (o.equals(elementData[index])) {
		    fastRemove(index);
		    return true;
		}
        }
	return false;
    }
删除某一对象,先找到该对象对应的下标,如果找到再通过下标删除。

addAll

public boolean addAll(Collection<? extends E> c) {
	Object[] a = c.toArray();
        int numNew = a.length;
	ensureCapacity(size + numNew);  // Increments modCount
        System.arraycopy(a, 0, elementData, size, numNew);
        size += numNew;
	return numNew != 0;
    }
将集合添加到list中,需要注意的是这个操作时不确定的当执行过程中被修改。

 public boolean addAll(int index, Collection<? extends E> c) {
	if (index > size || index < 0)
	    throw new IndexOutOfBoundsException(
		"Index: " + index + ", Size: " + size);

	Object[] a = c.toArray();
	int numNew = a.length;
	ensureCapacity(size + numNew);  // Increments modCount

	int numMoved = size - index;
	if (numMoved > 0)
	    System.arraycopy(elementData, index, elementData, index + numNew,
			     numMoved);

        System.arraycopy(a, 0, elementData, index, numNew);
	size += numNew;
	return numNew != 0;
    }
将集合添加到指定位置。该方法首先会扩容,然后将执行数组的拷贝。

总结

1. 从ArrayList的源码可以看出其底层是通过数组的方式来实现的,显然其访问速度比较快,相对来说插入和删除操作设计到数组的移动,故效率会低。

2. 虽然ArrayList会自动扩容,每次扩容和数组长度至少增加到原来的1.5倍+1,相对来说会有空间的浪费,而且频繁的扩容也会对性能产生影响,故在构造ArrayList的时候最好能指定长度。

避坑指南:STM32CubeMX配置USB虚拟串口时Heap Size设置的那些坑 本文深入剖析了使用STM32CubeMX配置USB虚拟串口时,因Heap Size设置不当导致设备无法识别的常见问题。文章从故障现象出发,详细解释了堆内存不足如何影响USB枚举过程,并提供了从内存布局分析、动态监控到系统化调试的完整解决方案,帮助开发者从根本上避免这一配置陷阱。 阅读详情

相关推荐

UE5实战:如何用Georeference插件搞定百度地图坐标转换(附完整代码)

本文详细解析了在UE5中使用Georeference插件实现百度地图坐标转换的全流程,包括BD-09到UE内部坐标的转换算法、UTM投影配置及性能优化技巧。通过完整代码示例和实战案例,帮助开发者高效解决数字孪生项目中的地理坐标转换难题。

weixin_30955617的博客 94

在JDK1.8中,ArrayList扩容机制Increments modCount与起始化讲解

在ArrayList中,起始化方式有两种: 1.调用无参的构造方法: public ArrayList() { //无参构造方法 this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; //将ArrayList起始化为一个名叫DEFAULTCAPACITY_EMPTY_ELEMENTDATA的对象 } ↓ 我们找到DEFAULTCAPACITY_EMPTY_ELEMENTDATA private static final Object[] D

m0_50666031的博客 750

MinerU与Docling:智能文档处理框架对比

本文对比分析了MinerU和Docling两大智能文档处理框架。MinerU专注于高精度PDF解析,采用多模态AI技术,在学术文献、金融报表等复杂文档处理上表现优异;Docling则定位企业级多格式文档处理平台,支持10+格式转换,更适合文档管理系统等场景。技术层面,MinerU基于VLM模型实现端到端处理,Docling采用插件化多后端架构。性能测试显示MinerU精度更高(95%+),但资源消耗较大;Docling处理速度更快(1-3秒/页),部署更灵活。

轩哥的个人研究和成长记录 1917

Java之ArrayList源码分析(第二篇:添加元素)

(注意:本文基于JDK1.8) ArrayList添加元素的方法,共计4个 ​ 我将依次分析它们是如何实现添加单个元素或者添加多个元素的…… add(E)方法分析 public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; return true; } ...

王员外的博客 5219

Js逆向抖音a_bogus --/* V 1.0.1.19-fix.01 */补环境

需要在addEventListener中补一个鼠标移动事件,不补这个环境,生成的值是假值,你拿去请求,响应200,但是没有数据,这个算是dy的最难发现的一个难点。dy这个,没有原形链检测,我只是习惯了这样补,对XMLHttpRequest进行重写,导出a_bogus.发现可以响应状态码200,而且可以获取数据,接着注释params中的a_bogus。在n.apply的下面插入上述代码,对a_bogus进行全局导出。如果没有,就多放几次断点,因为每个人的游览器不一样。必须触发至少一次鼠标事件,不触发不给过。

2302_76420666的博客 4205

保姆级教程:手把手配置MAX9295/9296 GMSL2-CSI2链路,搞定4LAN/1LAN模式与常见调试

本文提供MAX9295/9296 GMSL2-CSI2链路的详细配置教程,涵盖4LAN和1LAN模式的硬件连接、寄存器配置及调试技巧。通过实战案例和代码示例,帮助开发者快速实现高带宽视频传输,解决常见问题如信号同步和功耗优化,适用于车载摄像头和机器人视觉系统开发。

weixin_42561143的博客 436

Java面试专项——集合专题一(ArrayList)--万字读懂ArrayList底层原理

集合是JAVA重点中的重点也是面试官必会提问的一点,通常涉及到集合的面试题通常呈现以下几点:难度大、粒度细、重底层、涉及数据结构等基础知识。 本专题首先复习集合框架涉及到的数据结构基础知识,然后系统地回顾Java集合框架,最后解读一下涉及到Java集合的经典高频面试题。 一、数据结构回顾 二、集合框架回顾 如上图所示,集合分为两大类(Collection与Map),其中List接口与Set接口是Collection众多子接口中的两个。也可以说JAVA集合分为三大类---List、Set、M.

qq_42681787的博客 2277

【智能体评测】BrowserUse:一款超越 Anthropic Computer Use 的开源智能体

本文将全面介绍 BrowserUse 的核心功能、配置与使用方法,以及通过多场景测试评估其性能。

surfirst的博客 4099

ArrayList源码解析

ArrayList是我们使用频率非常高的一个集合,也是集合中相对比较简单的集合。是List接口的主要实现类。一般面试的时候经常会问到ArrayList和LinkedList的区别。 ArrayList: 底层是数组实现的,查找快,增删慢。 LinkedList: 底层是链表实现的,增删快,查找慢。 一.类结构 ArrayList是集合的一种,集合的最顶端抽象接口为Collection, Collection下面又有两个子接口,一个是List,一个是Set, List和Set的区别也经常别被问.

lsqingfeng的博客 1250

【问题解决】Python 运行报错 `ModuleNotFoundError` 全网最全解决方案,一文搞定所有导包问题

本文全面解析Python中常见的ModuleNotFoundError和ImportError问题,提供从基础到高级的解决方案。文章首先分析问题原因,包括模块未安装、环境不一致、路径问题等,然后给出7种解决方案:安装缺失模块、检查Python环境、使用虚拟环境、添加搜索路径、相对导入、setup.py安装本地包和使用__init__.py。针对Jupyter Notebook、Docker容器等常见场景提供专门解决方案,并推荐使用requirements.txt、pipenv等预防措施。最后分享调试技巧,帮

博客 917

将物理信息神经网络(PINN)应用于微通道湍流的拓扑优化,并结合COMSOL数据进行训练与快速预测

本文提出一种基于物理信息神经网络(PINN)的微通道散热器流场快速预测方法。通过有限组COMSOL仿真数据训练神经网络,结合Navier-Stokes方程和能量方程作为物理约束,构建可快速预测新拓扑结构下速度场和温度场的替代模型。该方法包含数据准备、网络构建、损失函数设计等关键步骤,利用自动微分计算方程残差,显著降低传统CFD优化的计算成本,实现秒级/分钟级的流场预测,为微通道散热器拓扑优化提供高效解决方案。

huanghm88的专栏 536

【JDK源码分析系列】ArrayList源码分析

【JDK源码分析系列】ArrayList源码分析 【1】ArrayList源码MCL视图 ArrayList的MCL视图如下图所示,包括内部类的MCL视图; 【2】ArrayList源码分析相关知识点总结 /** * 如果用transient声明一个实例变量,当对象存储时,它的值不需要维持; * 即用transient关键字标记的成员变量不参与序列化过程;...

CopperSun 技术博客 613

你以为你懂 Java 反射?看了这篇源码分析,我发现我以前都错了

摘要:本文讲述了一次生产环境Metaspace内存溢出的故障排查经历。事故源于一个通用数据导出功能中频繁使用反射调用method.invoke(),触发了JVM的"膨胀机制":当同一Method对象调用超过15次时,JVM会动态生成GeneratedMethodAccessor类,导致Metaspace被撑爆。文章分析了问题根源在于循环中反复调用getMethods()创建新Method对象,并提出了三种解决方案:缓存Method对象、改用MapStruct/MethodHandle工具

BUG猿的博客 770

Java基础之ArrayList源码分析

ArrayList是Java开发中使用比较频繁的一个类,通过对源码的解读,可以了解ArrayList的内部结构以及实现方法,清楚它的优缺点,以便我们在编程时灵活运用。

Soinice的博客 403

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

ArrayList 源码分析

例如,在 Java 中,如果一个对象包含一个基本数据类型的成员变量和一个引用类型的成员变量,进行浅拷贝时,基本数据类型的成员变量会被复制一份,而引用类型的成员变量只是复制了引用,两个对象仍然指向同一个引用对象。浅拷贝是创建一个新的对象,但是这个新对象的成员变量仍然指向原始对象的成员变量所指向的内存地址。也就是说,浅拷贝只是复制了对象的引用,而不是对象的实际内容。在其他编程语言中,如 Python、C++等,也有类似的深拷贝和浅拷贝的概念和实现方式,但具体的语法和方法会有所不同。方法进行实际的容量调整检查。

Wzideng@qq.com 982

pscad IEEE标准系统搭建说明

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

ArrayList的源码分析

来源:https://www.cnblogs.com/beppezhang/p/6560710.html 在项目中经常会用到list集合来存储数据,而其中ArrayList是用的最多的的一个集合,这篇博文主要简单介绍ArrayList的源码分析,基于JDK1.7: 这里主要介绍 集合 的属性,构造器,和方法:方法主要基于 add(E e),get(int index),remove(int i...

rentian1的博客 228

深度学习工具包 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")

131面试必问:ArrayList源码分析&手写ArrayList

简介 ArrayList是我们开发中非常常用的数据存储容器之一,其底层是数组实现的,我们可以在集合中存储任意类型的数据,ArrayList是线程不安全的,非常适合用于对元素进行查找,效率非常高。 线程安全性 对ArrayList的操作一般分为两个步骤,改变位置(size)和操作元素(e)。所以这个过程在多线程的环境下是不能保证具有原子性的,因此ArrayList在多线程的环境下是线程不安全的。 更多面试题:面试题内容聚合 源码分析 1. 属性分析 /** *默认初始化容量 ...

AI乔治 211

ArrayList常用方法及源码分析

ArrayList常用方法!!!!!!!!!!!

o676448的博客 418

Vector,ArrayList,Linkedlist源码分析

list接口和set集合

Cocobuhui的博客 974

Java源码分析之ArrayList

ArrayList源码分析 ArrayList作为一个java中对数据进行存储的容器,是java中List<E>接口的核心实现类 有句古话这么来着:“万变不离其宗”,观其源码,通俗的来说,ArrayList其实就是一个数组 数组众所周知,他的定义必须申请一个规定长度的存储空间,是顺序存储结构,但是ArrayList 似乎可以无限制的添加数据,这是为何,这其实是这种扩容机制系统悄悄地在背后棒你做了 就形成了表面上可以无限制地添加数据的现象 下面,让我们来看看ArrayList的源码分析.

qq_48201696的博客 442

ArrayList和LinkedList的区别和源码分析

从源码可以看出,ArrayList想要get(int index)元素时,直接返回index位置上的元素,而LinkedList需要通过for循环进行查找,虽然LinkedList已经在查找方法上做了优化,比如index < size / 2,则从左边开始查找,反之从右边开始查找,但是还是比ArrayList要慢。ArrayList自由性较低,因为它需要手动的设置固定大小的容量,但是它的使用比较方便,只需要创建,然后添加数据,通过调用下标进行使用;//向左挪一位,index位置原来的数据已经被覆盖了。

weixin_62198635的博客 732

java ArrayList源码分析

ArrayList是 Java 标准库中的一个非常常用的类,它实现了List接口,提供了一个动态数组的实现,可以用来存储一系列的元素。sizeArrayListArrayListArrayListsizeadd(E e)clear()size()ArrayList还实现了一些其他的内部方法和嵌套类,比如Itr(迭代器)、ListItr(列表迭代器)、SubList(子列表)等,这些类和方法支持ArrayList的高级操作,如迭代、元素搜索、子列表操作等。此外,ArrayList还重写了clone()

qq_36070104的博客 1093

ArrayList中add方法源码分析~

首先要明确ArrayList的底层实现是数组利用空参创建的集合时,在底层创建一个默认长度为0的数组添加第一个元素时,底层会创建一个新的长度为10的数组存满时,会扩容1.5倍如果一次添加多个元素,1.5倍还放不下,则新创建数组的长度以实际为准。

2501_90392153的博客 1905
上一篇: 为什么要写博客
下一篇: Vector源码分析
kevin0xFFFFFFFF
博客等级 码龄17年 3粉丝 79原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值