简单实现一个ArrayList

ArrayList是以底层为数组的集合 要想实现实现首先要明白ArrayList 的两个问题

①:扩容

②:如何限制集合中添加的类型

下面是代码实现

package com.tb.bean;

import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;

public class MyArrayList<E> {

	// 底层数组
	private E[] obj;

	// 当前的大小
	private int size;

	// 容量
	private int captial;

	// 当到达容量后每次扩容递增的空间大小
	private int limit;

	public MyArrayList() {
        // TODO Auto-generated constructor stub
        this(5);
    }

    public MyArrayList(Collection<E> collection) {



        int len = collection.size();
        this.captial = len + 5;
        Iterator<E> it = collection.iterator();
        this.obj = (E[]) new Object[captial];

        int i = 0;
        while (it.hasNext()) {
            Object object = it.next();
            this.obj[i++] = (E) object;
        }

        this.size = len;

        this.limit = 5;
    }
	
     public MyArrayList(int initnumber) {

		this.captial = initnumber;
		obj = (E[]) new Object[initnumber];
		this.limit = 5;
		
	}

	public boolean isEmpty() {
		return (size <= 0) ? true : false;
	}
	
	public int size(){
		if(this.obj == null){
			return -1;
		}
		return size;
	}

	public boolean add(E o) {

		boolean flag = false;

		if (this.obj == null) {
			throw new NullPointerException();
		}

		if (o == null) {
			return flag;
		}

		if (this.size >= this.captial) {		//由于是线程不安全的 防止异步加载时出现问题
			try {
				E[] temp = (E[]) new Object[this.captial + this.limit];	//这个try catch 块主要是防止 开数组时内存爆满出现问题
				
				System.arraycopy(this.obj, 0, temp, 0, this.captial);
				this.obj = temp;
				this.captial += limit;
			} catch (Throwable t) {	//可能是异常 也可能是error
				throw new RuntimeException(t);

			}
		}

		this.obj[size] = o;
		this.size++;
		flag = true;
		return flag;

	}

	public E get(int i) {

		if (i < 0 || i >= this.size) {
			throw new IndexOutOfBoundsException("逻辑越界");

		}

		return this.obj[i];

	}

	public boolean remove(int i) {

		boolean flag = true;
		if (i < 0 || i >= this.size) {
			throw new IndexOutOfBoundsException("逻辑越界");

		}
		try {
			for (int j = i; this.obj[j]!=null && j < this.size - 1; j++) {
				this.obj[j] = this.obj[j + 1];

			}

			this.size--;
			
			if (this.captial - this.size >= this.limit) {
				this.captial -= this.limit;
			}
			if (this.captial < 5) {
				this.captial = 5;
			}
			
			E[] temp = (E[]) new Object[this.captial];
			System.arraycopy(this.obj, 0, temp, 0, this.size);
			this.obj = temp;
		
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			flag = false;
		}
		return flag;
	}

}

如有问题 欢迎指出

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值