常见面试题手写ArrayList

public class MyArrayList {

	private Object[] elementData; // 底层数组
	private int size; // 数组大小

	// 获得数组大小
	public int size() {
		return size;
	}

	// 无参构造函数
	public MyArrayList() {
		this(10);
	}

	// 含参构造函数
	public MyArrayList(int initialCapacity) {
		if (initialCapacity < 0) {
			try {
				throw new Exception();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		elementData = new Object[initialCapacity];
	}

	// 判断是否为空
	public boolean isEmpty() {
		return size == 0;
	}

	// 根据下标获取对象
	public Object get(int index) {
		rangeCheck(index);
		return elementData[index];
	}

	public boolean add(Object obj) {
		ensureCapacity();
		elementData[size] = obj;
		size++;
		return true;
	}

	// 插入操作
	public void add(int index, Object obj) {
		rangeCheck(index);
		ensureCapacity();
		System.arraycopy(elementData, index, elementData, index + 1, size - index);
		elementData[index] = obj;
		size++;
	}

	// 删除操作
	public Object remove(int index) {
		rangeCheck(index);
		int arrnums = size - index - 1;
		Object oldValue = elementData[index];
		if (arrnums > 0) {
			System.arraycopy(elementData, index, elementData, index, arrnums);
		}
		elementData[--size] = null;
		return oldValue;
	}

	public boolean remove(Object obj) {
		for (int i = 0; i < size; i++) {
			if (get(i).equals(obj)) {
				remove(i);
			}
			break;
		}
		return true;
	}

	public Object set(int index, Object obj) {
		rangeCheck(index);
		Object oldValue = elementData[index];
		elementData[index] = obj;
		return oldValue;
	}

	// 检查容量,必要时扩容处理
	private void ensureCapacity() {
		if (size == elementData.length) {
			Object[] newArray = new Object[size + (size >> 1)];
			System.arraycopy(elementData, 0, newArray, 0, size);
			elementData = newArray;
		}
	}

	// 检查下标是否合法
	public void rangeCheck(int index) {
		if (index < 0 || index >= size) {
			try {
				throw new Exception();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) {
		MyArrayList mylist = new MyArrayList();
		mylist.add("哈哈");
		mylist.add("呵呵");
		mylist.add("哦哦");
		mylist.add("哈哈");
		mylist.add(1, "手写代码");
		String old = (String) mylist.remove(3); // 返回的是旧值
		System.out.println(old);
		System.out.println(mylist.remove("哦哦"));
		System.out.println(mylist.isEmpty());
		System.out.println(mylist.get(1));
		System.out.println(mylist.size());
		System.out.println(mylist.set(2, "你好啊")); // 返回旧值
		System.out.println(mylist.get(2));
	}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值