Java容器---MyArrayList

自定义容器ArrayList,实现部分功能

/**
 * 编程实现ArrayList
 * @author Administrator
 *
 */
public class MyArrayList {
	//创建目标数组
	private Object[] elementDate;
	//数组长度
	private static int size;
	//获取长度
	public int size(){
		return size;
	}
	//无参构造方法,默认长度10
	public MyArrayList(){
		this(10);
	}
	// 有参构造方法,初始化
	public MyArrayList(int initicalCapacity){
		if (initicalCapacity<0) {
			try {
				throw new Exception();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		elementDate = new  Object[initicalCapacity];
	}
	//在数组末尾增加指定对象
	public void add(Object obj){
		ensureCapacity();
		elementDate[size++]=  obj;
	}
	//在索引位置增加指定对象,索引位置及之后的元素向后移动一位
	public void add(int index,Object obj){
		ensureCapacity();
		indexJudgement(index);
		//System.arraycopy(等待复制的数组, 开始复制的位置, 目标数组, 复制到目标数组的位置, 复制长度);
		System.arraycopy(elementDate, index, elementDate, index+1, size-index);
		elementDate[index] = obj;
		size++;
	}
	//将索引位置对象设置为指定的对象
	public Object set(int index,Object obj){
		indexJudgement(index);
		Object oldValue = elementDate[index];
		elementDate[index] = obj;
		return oldValue;
	}
	//判断数组是否为空
	public boolean isEmpty(){
		return size==0;
	}
	//获取索引位置对象
	public Object get(int index){
		indexJudgement(index);
		return elementDate[index];
	}
	//移除索引位置对象
	public void remove(int index){
		indexJudgement(index);
		int moveNum = size-index-1;
		System.arraycopy(elementDate, index+1, elementDate, index, moveNum);
		elementDate[--size]=null;
	}
	//移除第一个相同的对象
	public boolean remove(Object obj){
		for (int i = 0; i < elementDate.length; i++) {
			if (get(i).equals(obj)) {
				remove(i);
				//只移除第一个相同的对象,使用return结束方法的功能实现
				return true;
			}
		}
		return false;
	}
	//数组扩容
	public void ensureCapacity(){
		if (size+1>elementDate.length) {
			Object[] newArray = new Object[size*2+1];
//			System.arraycopy(elementDate, 0, newArray , 0, elementDate.length);
			for (int i = 0; i < elementDate.length; i++) {
				newArray [i] = elementDate[i];
				
			}
			elementDate = newArray;
		}
	}
	//索引越界判断
	public void indexJudgement(int index){
		if (index<0||index>=size) {
			try {
				throw new Exception();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	public static void main(String[] args) {
	//	List list = new ArrayList();
		MyArrayList list = new MyArrayList(3);
		list.add(555);
		list.add(0,1111);
		list.set(1, "sss");
		for (int j = 0; j < size; j++) {
			System.out.println(list.get(j));
		}
		
		
	}
}

猜你喜欢

转载自blog.csdn.net/qq_30007589/article/details/80851195