JAVA 用数组实现 ArrayList
我们知道 ArrayList 是一个集合,它能存放各种不同类型的数据,而且其容量是自动增长的。那么它是怎么实现的呢?
其实 ArrayList 的底层是用 数组实现的。我们查看 JDK 源码也可以发现。而用数组实现集合的原理有两点:
1、能自动扩容
2、能存放不同类型的数据
这两点我们是这样解决的:
1、当一个数据存放满了,我们就将这个数据复制到一个新的数组中,而这个新的数组容量要比原数组大。通过这样不断的扩大数组长度,也就是集合的容量。那么这里我们用到了这个方法 System.arraycopy
完整的写法为:public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
参数
@ src -- 这是源数组 @ srcPos -- 这是源数组中的起始位置 @dest -- 这是目标数组 @ destPos -- 这是目标数据中的起始位置 @ length -- 这是一个要复制的数组元素的数目
int arr1[] = {0,1,2,3,4,5};
int arr2[] = {0,10,20,30,40,50};
System.arraycopy(arr1,0,arr2,1,2);
//结果为:arr2 = [0,0,1,30,40,50];
2、第二个问题,我们只需要声明为 Object 类型的数组就可以了。
完整代码如下:
package com.ys.collection;
public class MyArrayList {
//用于存储数据
private transient Object[] data = null;
//集合的元素个数
private int size = 0;
//定义一个常量为 10.(后面用于定义默认的集合大小)
private static final int DEFAULT_CAPACITY = 10;
/***
* 有参构造函数
* 指定数组的大小
* @param length
*/
public MyArrayList(int initialCapacity){
if(initialCapacity < 0){
throw new IllegalArgumentException("非法的集合初始容量值 Illegal Capacity: "+
initialCapacity);
}else{
//实例化数组
this.data = new Object[initialCapacity];
}
}
/***
* 无参构造函数
* 指定数组的初始大小为 10
*/
public MyArrayList(){
this(DEFAULT_CAPACITY);
}
/***
* 1、复制原数组,并扩容一倍
* 2、复制原数组,并扩容一倍,并在指定位置插入对象
* @param index
* @param obj
*/
public void checkIncrease(int index,Object obj){
if(size >= data.length){
//实例化一个新数组
Object[] newData = new Object[size*2];
if(index == -1 && obj == null){
System.arraycopy(data, 0, newData, 0, size);
}else{
//将要插入索引位置前面的对象 拷贝
System.arraycopy(data, index, newData, index+1, size-index);
}
//将 newData 数组赋值给 data数组
data = newData;
newData = null;
}
}
/***
* 获取数组的大小
* @return
*/
public int getSize(){
return this.size;
}
/***
* 根据元素获得在集合中的索引
* @param o
* @return
*/
public int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < data.length; i++)
if (data[i]==null)
return i;
} else {
for (int i = 0; i < data.length; i++)
if (o.equals(data[i]))
return i;
}
return -1;
}
/***
* 在尾部添加元素
* @param obj
* @return
*/
public boolean add(Object obj){
//检查是否需要扩容
checkIncrease(-1, null);
data[size++] = obj;
return true;
}
/**
* 判断给定索引是否越界
* @param index
* @return
*/
public boolean checkIndexOut(int index){
if(index > size || index < 0){
throw new IndexOutOfBoundsException("指定的索引越界,集合大小为:"+size+",您指定的索引大小为:"+index);
}
return true;
}
public boolean add(int index,Object obj){
//如果给定索引长度刚好等于原数组长度,那么直接在尾部添加进去
if(index == size){
add(obj);
}
//checkIndexOut()如果不抛异常,默认 index <=size,且 index > 0
else if(checkIndexOut(index)){
if(size < data.length){
System.arraycopy(data, index, data, index+1, size-index);
data[index] = obj;
}else{
//需要扩容
checkIncrease(index, obj);
}
size++;
}
return true;
}
/***
* 根据索引获得元素
* @param index
* @return
*/
public Object get(int index){
checkIndexOut(index);
return data[index];
}
/***
* 删除所有元素
*/
public void removeAll(){
for(int i = 0 ; i < data.length ; i++){
data[i] = null;
}
}
/***
* 根据索引删除元素
* @param index
* @return
*/
public Object remove(int index){
if(index == size+1){
throw new IndexOutOfBoundsException("指定的索引越界,集合大小为:"+size+",您指定的索引大小为:"+index);
}else if(checkIndexOut(index)){
//保存对象
Object obj = data[index];
if(index == size){
data[index] = null;
}else{
//将后边的数组向前移动一位
System.arraycopy(data, index+1, data, index, size-index);
}
size--;
return obj;
}
return null;
}
/***
* 删除指定的元素,删除成功返回 true,失败返回 false
* @param obj
* @return
*/
public boolean remove(Object obj){
for(int i = 0 ; i < size ; i++){
if(obj.equals(data[i])){
remove(i);
return true;
}
}
return false;
}
/***
* 在指定位置修改元素,通过索引,修改完成后返回原数据
* @param index
* @param obj
* @return
*/
public Object change(int index,Object obj){
checkIndexOut(index);
Object oldObj = data[index];
data[index] = obj;
return oldObj;
}
/***
* 查看集合中是否包含某个元素,如果有,返回 true,没有返回 false
* @param obj
* @return
*/
public boolean contain(Object obj){
for(int i = 0 ; i < data.length ; i++){
if(obj.equals(data[i])){
return true;
}
}
return false;
}
public static void main(String [] args){
MyArrayList my = new MyArrayList();
//System.out.println(my.data.length);
my.add(0,3);
//System.out.println(my.getSize());
my.add(0,4);
//System.out.println(my.getSize());
my.add(0,5);
//my.removeAll();
//my.remove(2);
//System.out.println(my.get(2));
System.out.println(my.indexOf(null));
System.out.println(my.contain(2));
for(int i = 0 ; i < my.data.length ; i++){
System.out.println(my.data[i]);
}
}
}
JAVA 用数组实现 ArrayList的更多相关文章
- 将java中数组转换为ArrayList的方法实例(包括ArrayList转数组)
方法一:使用Arrays.asList()方法 1 2 String[] asset = {"equity", "stocks", "gold&q ...
- java的数组和arraylist
1.数组 1.0 一开始就错了 int a[8]; //没有像C在内存中开辟了8个区域 改: int a[] = {1,2,3} ; System.out.println(a.length); ...
- Java中Array与ArrayList的10个区别
Array和ArrayList都是Java中两个重要的数据结构,在Java程序中经常使用.并且ArrayList在内部由Array支持,了解Java中的Array和ArrayList之间的差异对于成为 ...
- 在Java中怎样把数组转换为ArrayList?
翻译自:How to Convert Array to ArrayList in Java? 本文分析了Stack Overflow上最热门的的一个问题的答案,提问者获得了很多声望点,使得他得到了在S ...
- [转]Java中怎样把数组转换为ArrayList
方法汇总: Element[] array = {new Element(1),new Element(2),new Element(3)}; ArrayList<Element> arr ...
- Java基础(七)泛型数组列表ArrayList与枚举类Enum
一.泛型数组列表ArrayList 1.在Java中,ArrayList类可以解决运行时动态更改数组的问题.ArrayList使用起来有点像数组,但是在添加或删除元素时,具有自动调节数组容量的功能,而 ...
- 数组容器(ArrayList)设计与Java实现,看完这个你不懂ArrayList,你找我!!!
数组容器(ArrayList)设计与Java实现 本篇文章主要跟大家介绍我们最常使用的一种容器ArrayList.Vector的原理,并且自己使用Java实现自己的数组容器MyArrayList,让自 ...
- Java学习笔记51:数组转ArrayList和ArrayList转数组技巧
ArrayList转数组: public class Test { public static void main(String[] args) { List<String> list = ...
- Java中List,ArrayList、Vector,map,HashTable,HashMap区别用法
Java中List,ArrayList.Vector,map,HashTable,HashMap区别用法 标签: vectorhashmaplistjavaiteratorinteger ArrayL ...
随机推荐
- JavaWeb框架_Struts2_(六)----->Struts2的输入校验
1. 输入校验章节目录 输入校验概述 客户端校验 服务器端校验 手动编程校验 重写validate方法 重写validateXxx()方法 输入校验流程 校验框架校验 Struts2 内置的校验器 常 ...
- 【原创】1、简单理解微信小程序
先看下网站的运行方式: 而小程序是这样: what?就这样?是的,就这样.那小程序官方提供的Wafer,还有Wafer2...想太多了,抛弃它们吧.不应当为了解决一个简单的旧问题而去整一个复杂的新问题 ...
- 学问Chat UI(4)
前言 写这个组件是在几个月前,那时候是因为老大讲RN项目APP的通讯聊天部分后面有可能自己实现,让我那时候尝试着搞下Android通讯聊天UI实现的部分,在这期间,找了不少的Android原生项目:蘑 ...
- java基础部分的简单应用
牛刀小试,MMP:嘿嘿,如有转载,请声明地址http://www.cnblogs.com/jinmoon/: 图形类,点类,三角形类,汽车类,接口:运用继承,抽象类,接口,多态:已知点类三点,输出三点 ...
- slurm任务调度系统部署和测试(一)
1.概述 本博客通过VMware workstation创建了虚拟机console,然后在console内部创建了8台kvm虚拟机,使用这8台虚拟机作为集群,来部署配置和测试slurm任务调度系统. ...
- poj 2271HTML
poj2271 HTML Description If you ever tried to read a html document on a Macintosh, you know how hard ...
- Linux Rsync备份服务介绍及部署守护进程模式
rsync介绍 rsync是一款开源的.快速的.多功能的.可实现全量及增量的本地或远程数据同步备份工具 在常驻模式(daemon mode)下,rsync默认监听TCP端口873,以原生rsync传输 ...
- js模拟静态方法
//模拟静态 var Animal = function(name){ this.name = name; Animal.instanceCounter ++; }; Animal.instanceC ...
- Intellij IDEA安装golang插件
原文作者:Jianan - qinxiandiqi@foxmail.com 原文地址:http://blog.csdn.net/qinxiandiqi/article/details/50319953 ...
- git for c#,子文件的加入
private static void SubDirFile() { string wkDir = @"E:\DotNet2010\单位project\Git.Client\lib2Test ...