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 ...
随机推荐
- Cesium基础使用介绍
前言 最近折腾了一下三维地球,本文简单为大家介绍一款开源的三维地球软件--Cesium,以及如何快速上手Cesium.当然三维地球重要的肯定不是数据显示,这只是数据可视化的一小部分,重要的应该是背后的 ...
- hdu 1150 Machine Schedule 最小覆盖点集
题意:x,y两台机器各在一边,分别有模式x0 x1 x2 ... xn, y0 y1 y2 ... ym, 现在对给定K个任务,每个任务可以用xi模式或者yj模式完成,同时变换一次模式需要重新启动一次 ...
- 51Nod 1293 球与切换器 DP分类
基准时间限制:1 秒 空间限制:131072 KB 有N行M列的正方形盒子.每个盒子有三种状态0, -1, +1.球从盒子上边或左边进入盒子,从下边或右边离开盒子.规则: 如果盒子的模式是-1,则 ...
- HDU2191--多重背包(二进制分解+01背包)
悼念512汶川大地震遇难同胞--珍惜现在,感恩生活 Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Jav ...
- php IP转换整形(ip2long)
如何将四个字段以点分开的IP网络址协议地址转换成整数呢?PHP里有这么一个函数ip2long.比如 <?php echo ip2long("10.2.1.3"); ?> ...
- 【JDK1.8】JDK1.8集合源码阅读——IdentityHashMap
一.前言 今天我们来看一下本次集合源码阅读里的最后一个Map--IdentityHashMap.这个Map之所以放在最后是因为它用到的情况最少,也相较于其他的map来说比较特殊.就笔者来说,到目前为止 ...
- 》》HTML5 移动页面自适应手机屏幕四类方法
1.使用meta标签:viewport H5移动端页面自适应普遍使用的方法,理论上讲使用这个标签是可以适应所有尺寸的屏幕的,但是各设备对该标签的解释方式及支持程度不同造成了不能兼容所有浏览器或系统. ...
- SQL或HQL预编译语句,可以防止SQL注入,可是不能处理%和_特殊字符
近期项目在做整改,将全部DAO层的直接拼接SQL字符串的代码,转换成使用预编译语句的方式.个人通过写dao层的单元測试,有下面几点收获. dao层代码例如以下 //使用了预编译sql public L ...
- Bayan 2015 Contest Warm Up D题(GCD)
D. CGCDSSQ time limit per test 2 seconds memory limit per test 256 megabytes input standard input ou ...
- 25个增强iOS应用程序性能的提示和技巧(0基础篇)
在开发iOS应用程序时,让程序具有良好的性能是非常关键的. 这也是用户所期望的,假设你的程序执行迟钝或缓慢,会招致用户的差评.然而因为iOS设备的局限性,有时候要想获得良好的性能,是非常困难的. 在开 ...