package com.mashibing.springbootdatasourcedemo2.shouxie;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
/**
* <简述> 手写一个arrayList
* <详细描述>
*
* @author LiuShanshan
* @version $Id$
*/
public class ArrayListTest implements Serializable{
// 默认容量
private static final int DEFAULT_RONLIANG = 10;
// 如果没有在创建对象的时候赋值容量,则给一个空的数组
private static final Object[] DEFUALT_ARRAY = {};
// 放数据的数组
private Object[] execData;
// 最小容量
private int size;
ArrayListTest(){
execData = DEFUALT_ARRAY;
}
ArrayListTest(int ronliang){
execData = new Object[]{ronliang};
}
public boolean add(Object e){
// 判断容量是否够使用,保证容量够使用
ensureCapacityInternal(size + 1);
execData[size++] = e;
return true;
}
public void ensureCapacityInternal(int size){
// 先判断当前数组是否有容量
if(execData.length == DEFUALT_ARRAY.length){
// 如果没有容量,则比较10和size的大小
size = Math.max(DEFAULT_RONLIANG, size);
}
// 如果当前的size 大于 容量的话则扩容
int oldLength = execData.length;
if(oldLength - size < 0){
// 需要扩容
int newlenth = oldLength + oldLength/2;
// 如果新容量小于最小容量,则使用最小容量
if(newlenth < size){
newlenth = size;
}
// 改变原始数组的长度,将newlength放进去
execData = Arrays.copyOf(execData, newlenth);
}
}
public static void main(String[] args) {
ArrayListTest arrayListTest = new ArrayListTest(5);
arrayListTest.add("测试数据1");
arrayListTest.add("测试数据2");
System.out.println(arrayListTest);
}
}
手写一个arrayList
最新推荐文章于 2022-04-15 11:45:28 发布