小伙伴来自己实现一个ArrayList

想来去年实习面试的时候,有公司发来面试题,要求自己实现一个List,当时觉得好难好难,现工作了,有空回来补习一下数据结构,在此与各位小伙伴共勉,望大家多多指教。

代码如下:

package com.david.duan;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class MyArrayList implements Iterable<Student>{

	//给List设定默认大小
	private static final int DEFAULT_SIZE = 10;
	//用于存储list的大小
	private int size;
	//原生数组
	private Student [] students;
	//构造函数
	public MyArrayList () {
		clear ();
	}
	
	private void clear() {
		size = 0;
		ensureCapacity(DEFAULT_SIZE);
	}
	
	public int size () {
		return size;
	}
	
	public boolean isEmplty () {
		return size() == 0;
	}
	
	public void trimToSize () {
		ensureCapacity (size());
	}
	//返回固定下标的元素
	public Student get (int idx) {
		if ( idx < 0 || idx >= size()  )
			throw new ArrayIndexOutOfBoundsException();
		return students[idx];
	}
	//在固定位置插入元素,并返回之前的元素
	public Student set (int idx, Student news) {
		if ( idx < 0 || idx >= size()  )
			throw new ArrayIndexOutOfBoundsException();
		Student oldStudent  = students[idx];
		students[idx] = news;
		return oldStudent;
	}
	//当增加元素到list时,如果数组长度不够,用此扩充大小
	public void ensureCapacity (int newCapacity) {
		if (newCapacity < size)
			return;
		Student [] oldStudents = students;
		students = (Student []) new Object[newCapacity];
		for (int i = 0; i < size(); i++) {
			students[i] = oldStudents[i];
		}
			
	}
	
	public boolean add(Student student) {
		add(size(), student);
		return true;
	}
	
	public void add (int idx, Student student) {
		if (students.length == size())
			ensureCapacity(size() * 2 +1);
		for (int i = size; i > idx; i--)
			students[i] = students [i -1];
		students [idx] = student;
		
		size ++;
	}
	//删除元素
	public Student remove(int idx) {
		Student removeStudent = students[idx];
		for (int i = idx; i < size; i++) {
			students [i] = students[i+1];
		}
		size --;
		return removeStudent;
	}
	
	//实现迭代器接口
	@Override
	public Iterator<Student> iterator() {
		return new ArrayListIterator();
	}
    private class ArrayListIterator implements java.util.Iterator<Student> {

    	private int current = 0;
    	
		@Override
		public boolean hasNext() {
			return current < size();
		}

		@Override
		public Student next() {
			if (!hasNext()) {
				throw new NoSuchElementException();
			}
			return students[current +1];
		}

		@Override
		public void remove() {
			MyArrayList.this.remove( --current);
		}
    	
    }
}
以上的实现基本仿造ArrayList的源码实现,但由于水平有限,很多细节考虑不周,望小伙伴们多多包涵。Collection的API存在某种错误检测以保证合理的限界,为了把精力放在编写迭代器的基本方面,小鸟并没有检测可能使得迭代器结构无效的修改,也没有检测非法的迭代器remove方法。如果有机会,我会在接下来的LinkedList实现中把他完善,谢谢小伙伴们的继续支持。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值