ArrayList中的remove方法是如何实现的
2013-05-04 18:17
344 查看
ArrayList
remove方法的源码: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; }
首先当然是找到要删除的对象的下标,毕竟在java中List的实现是使用数组来实现的,一个数组,你说要删掉某个元素,那是什么意思,意思就是把要删除元素下标之后的元素都移前一位:
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; // Let gc do its work }
elementData[--size] = null;把要删除元素之后的元素都前移一位之后,最后一个元素都让要设置为null了
下面是TestSystemCopy.java:
package testSystem; public class TestSystemCopy { public static void main(String[] args) { String[] strArr = new String[]{ "1","2","3", "4","5","6", "7","8","9" }; //把下标为4的元素往前移一位 System.arraycopy(strArr, 3, strArr, 2, strArr.length -3); strArr[strArr.length-1] = null; for(int i = 0; i < strArr.length; i++){ System.out.println(strArr[i]); } } }ArrayList中是使用数组来实现的
相关文章推荐
- (日常打卡)自定义的一个模仿ArrayList的类, 你需要实现其中的add, get, remove , 等方法
- angularjs项目的页面跳转如何实现(5种方法)
- 如何在ASP.net中实现限制一个用户名在多个客户端IE登陆的方法
- 如何实现CSS居中?–CSS居中常用方法
- 如何实现window系统cmd环境下从远程FTP服务器上下载文件的方法
- 方法:如何解决用MFC实现的ping功能中把目标主机不可到达的当成ping通的问题
- 如何通过鼠标或者键盘监听器,实现组建特有的监听方法
- 在Activity之间如何传递数据,请尽可能说出你所知道的传递数据的方法,并详细描述其实现过程。
- php如何实现页面回退的两种方法
- js如何实现设计模式中的模板方法
- Android Studio implements 一个类后如何实现这个类的方法
- 【实践】用js 实现 jq 的removeClass 方法
- Java如何实现可折叠Panel方法示例
- 本文通过举例的方式来教你如何在Oracle中实现SELECT TOP N的方法(转)
- 如何实现多个线程同步 (2013-11-10 12:07:24)转载▼ 标签: it 在编写一个类时,如果该类中的代码可能运行于多线程环境下,那么就要考虑同步的问题,Java实现线程同步的方法很多
- 说说如何使用 Java 的原生方法实现 AES 算法
- 解析如何正确使用SqlConnection的实现方法
- [转载]EasyDarwin手机直播是如何实现的快速显示视频的方法
- Android来电铃声默认设置的实现方法与如何设置语音来电的默认铃声
- 转 如何用mt7620方案的rt2860v2驱动实现wifi探针功能,网上能搜到一些方法,但是讲的好模糊?