我们知道 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的更多相关文章

  1. 将java中数组转换为ArrayList的方法实例(包括ArrayList转数组)

    方法一:使用Arrays.asList()方法   1 2 String[] asset = {"equity", "stocks", "gold&q ...

  2. java的数组和arraylist

    1.数组 1.0   一开始就错了 int a[8];   //没有像C在内存中开辟了8个区域 改: int a[] = {1,2,3} ; System.out.println(a.length); ...

  3. Java中Array与ArrayList的10个区别

    Array和ArrayList都是Java中两个重要的数据结构,在Java程序中经常使用.并且ArrayList在内部由Array支持,了解Java中的Array和ArrayList之间的差异对于成为 ...

  4. 在Java中怎样把数组转换为ArrayList?

    翻译自:How to Convert Array to ArrayList in Java? 本文分析了Stack Overflow上最热门的的一个问题的答案,提问者获得了很多声望点,使得他得到了在S ...

  5. [转]Java中怎样把数组转换为ArrayList

    方法汇总: Element[] array = {new Element(1),new Element(2),new Element(3)}; ArrayList<Element> arr ...

  6. Java基础(七)泛型数组列表ArrayList与枚举类Enum

    一.泛型数组列表ArrayList 1.在Java中,ArrayList类可以解决运行时动态更改数组的问题.ArrayList使用起来有点像数组,但是在添加或删除元素时,具有自动调节数组容量的功能,而 ...

  7. 数组容器(ArrayList)设计与Java实现,看完这个你不懂ArrayList,你找我!!!

    数组容器(ArrayList)设计与Java实现 本篇文章主要跟大家介绍我们最常使用的一种容器ArrayList.Vector的原理,并且自己使用Java实现自己的数组容器MyArrayList,让自 ...

  8. Java学习笔记51:数组转ArrayList和ArrayList转数组技巧

    ArrayList转数组: public class Test { public static void main(String[] args) { List<String> list = ...

  9. Java中List,ArrayList、Vector,map,HashTable,HashMap区别用法

    Java中List,ArrayList.Vector,map,HashTable,HashMap区别用法 标签: vectorhashmaplistjavaiteratorinteger ArrayL ...

随机推荐

  1. HDU 1060 Leftmost Digit 基础数论

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1060   这道题运用的是数学方法. 假设S=n^n.两边同时取对数,得到lgS=nlgn.即有S=10 ...

  2. Yahoo网站性能优化的34条军规

    1.尽量减少HTTP请求次数 终端用户响应的时间中,有80%用于下载各项内容,这部分时间包括下载页面中的图像.样式表.脚本.Flash等.通过减少页面中的元素可以减少HTTP请求的次数,这是提高网页速 ...

  3. form表单数据封装成json格式并提交给服务器

    1.jsp代码,form表单: <form action="#" id="costForm"> <input type="hidde ...

  4. Postgres是如何管理空值的

    创建表test,y字段插入null. test=# create table test(x bigint,y bigint,z text); CREATE TABLE test=# insert in ...

  5. 响应式框架Bootstrap栅格系统

    <!DOCTYPE html><html><head lang="en">    <meta charset="UTF-8&qu ...

  6. 》》stroll--各种特效下拉菜单

    <!doctype html> <html lang="en"> <head> <meta charset="utf-8&quo ...

  7. Android安全专项-利用androguard分析微信

    androguard Androguard经常使用API学习1 安装 做 Android 安全測试之前你应该知道的工具 (一) 分析 ./androlyze.py -s进入分析的交互界面 然后运行 a ...

  8. C#调用RESTful API

    如今非常多的网络服务都用RESTful API来实现. 比方百度的搜索推广API介绍使用Rest原因:REST+JSON风格的API相比SOAP+XML,优点是:调用更加灵活.也更easy扩展:JSO ...

  9. android项目 之 记事本(11) ----- 加入数据库

    本文是自己学习所做笔记.欢迎转载.但请注明出处:http://blog.csdn.net/jesson20121020 通过之前的10节,已实现了记事本的大部分功能,有加入拍照.加入照片,加入录音,加 ...

  10. IIS 服务或万维网公布服务,或者依赖这 服务可能在启动期间错误发生或者已禁用

    作者:jiankunking 出处:http://blog.csdn.net/jiankunking 详细错误信息例如以下: 解决方式: 在服务中禁用下面3个服务自己主动启动: Net.Msmq Li ...