12、自己实现的ArrayList

1、自己实现的ArrayList的代码如下

package com.baowei.test;

public class MyArrayList<E> {
	// 表示当前的存储元素的大小
	private int size = 0;
	// 表示容量的大小
	private int capacity = 10;
	// 数值,用于保存数据
	private E[] values = null;

	// 无参构造函数
	@SuppressWarnings("unchecked")
	public MyArrayList() {
		values = (E[]) new Object[capacity];
	}

	// 有参构造函数
	@SuppressWarnings("unchecked")
	public MyArrayList(int capacity) {
		this.capacity = capacity;
		values = (E[]) new Object[capacity];
	}

	public void add(E e) {
		if (e == null) {
			throw new RuntimeException("输入的元素为Null...");
		}
		if (size >= capacity) {
			// 重新构造大小
			enlargeCapacity();
		}
		// 放入元素
		values[size] = e;
		size++;
	}

	public E get(int index) {
		if (index < 0 || index >= size) {
			throw new RuntimeException("下标异常... ");
		}
		// 放入元素
		return values[index];
	}

	public E remove(int index) {
		if (index < 0 || index >= size) {
			throw new RuntimeException("下标异常... ");
		}

		for (int i = index; i < size - 1; i++) {
			values[i] = values[i + 1];
		}
		values[size - 1] = null;
		size--;
		return values[index];

	}

	@SuppressWarnings("unchecked")
	private void enlargeCapacity() {
		capacity = capacity * 2;
		E[] tmpValues = (E[]) new Object[capacity];
		System.arraycopy(values, 0, tmpValues, 0, size);
		values = tmpValues;
	}

	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append("[");
		for (int i = 0; i < size; i++) {
			sb.append(values[i]).append(",");
		}
		if (size > 0) {
			sb.deleteCharAt(sb.length() - 1);
		}
		sb.append("]");
		return sb.toString();
	}

	public static void main(String[] args) {
		MyArrayList<String> myList = new MyArrayList<String>();
		myList.add("0");
		myList.add("1");
		myList.add("2");
		myList.add("3");
		myList.add("4");
		myList.add("5");
		myList.add("6");
		myList.add("7");
		myList.add("8");
		myList.remove(7);
		System.out.println(myList.toString());
	}
}

2、参考的博客地址

http://blog.csdn.net/fenglibing/article/details/14166011



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值