博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
ArrayList源码常用方法注意点
阅读量:2065 次
发布时间:2019-04-29

本文共 2260 字,大约阅读时间需要 7 分钟。

扩容:

private void grow(int minCapacity) {        // overflow-conscious code        int oldCapacity = elementData.length;        int newCapacity = oldCapacity + (oldCapacity >> 1); //扩容长度计算        if (newCapacity - minCapacity < 0)            newCapacity = minCapacity;        if (newCapacity - MAX_ARRAY_SIZE > 0)            newCapacity = hugeCapacity(minCapacity);        // minCapacity is usually close to size, so this is a win:        elementData = Arrays.copyOf(elementData, newCapacity);    }

contains:

public boolean contains(Object o) {   return indexOf(o) >= 0;}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])) //注意点:自己的对象是否实现了equals           return i;   }   return -1;}

删除元素remove

 1.按index方式删除

public E remove(int index) {        rangeCheck(index);        modCount++;        E oldValue = elementData(index);        int numMoved = size - index - 1;        if (numMoved > 0)            System.arraycopy(elementData, index+1, elementData, index,                             numMoved); //注意删除的方式是数组往前移 所以便利删除不从新计算下标会有问题        elementData[--size] = null; // clear to let GC do its work        return oldValue;    }

2.对象方式删除

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])) { //比较的时候equals                    // 用index方式删除                    fastRemove(index);                    return true;                }        }        return false;    }    /*     * Private remove method that skips bounds checking and does not     * return the value removed.     */    private void fastRemove(int index) {        modCount++;        int numMoved = size - index - 1;        if (numMoved > 0)            System.arraycopy(elementData, index+1, elementData, index,                             numMoved);        elementData[--size] = null; // clear to let GC do its work    }

 

转载地址:http://ebwmf.baihongyu.com/

你可能感兴趣的文章
计算机底层是什么东西?
查看>>
关于PHP几点建议
查看>>
硬盘的接口、协议
查看>>
安装系统之一 U盘启动盘制作
查看>>
安装系统之二 U盘启动盘制作---UEFI版
查看>>
安装系统之四 U盘装GHOST XP教程
查看>>
安装系统之五 U盘装原版XP教程
查看>>
安装系统之六 U盘装GHOST WIN7教程
查看>>
安装系统之八 U盘装GHOST WIN8教程
查看>>
安装系统之九 U盘装原版WIN8教程
查看>>
安装系统之三 U盘启动盘建立磁盘分区教程
查看>>
系统安装之十 U盘安装原版win10
查看>>
安装系统之十一 UEFI和Legacy及UEFI+Legacy启动的区别
查看>>
树莓派屏幕---------Android手机作为树莓派的屏幕
查看>>
嵌入式 知识点 积累 (一)
查看>>
嵌入式 知识积累 (二) 之 三个学习阶段
查看>>
嵌入式 知识积累(三) 之 基本技能
查看>>
嵌入式 知识积累(四) 之 硬件开发的基本过程
查看>>
嵌入式 知识积累(五)之硬件工程师具备基本技能
查看>>
中小型园区网络的设计与实现 (一)
查看>>