手写一个arrayList

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);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值