1. 程式人生 > >自己實現一個簡單ArrayList

自己實現一個簡單ArrayList

廢話不多說直接上程式碼

package com.zgs.utils;

import java.util.ArrayList;

import org.aspectj.weaver.patterns.ExactAnnotationFieldTypePattern;

/**
 * 自己實現ArrayList
 * @author Administrator
 *
 */
public class MyArrayList {
	private Object[] elementData;
	private int size;
	public MyArrayList(int initialCapacity){
		if(initialCapacity<0){
			try {
				throw new Exception();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		elementData=new Object[initialCapacity];
	}
	public MyArrayList(){
		this(10);//預設是十
	}
	//集合的add方法
	public boolean add(Object o){
		//給資料擴容
		if(size==elementData.length){
			Object[] ob= new Object[size*2+1];
			//將資料拷貝到新陣列中
			System.arraycopy(elementData, 0, ob,0, elementData.length);
			elementData=ob;
		}
		elementData[size++]=o;
		return true;
	}
	public Object get(int index){
		if(index<0 || index>=size)
			throw new OutOfMemoryError("越界了");
		
		return elementData[index];
	}
	public void remove(int index){
		if(index<0 || index>=size)
			throw new OutOfMemoryError("越界了");
		int m=size-index-1;
		if(m>0){
			System.arraycopy(elementData, index+1, elementData, index, m);
		}
		elementData[--size]=null;
	}
	public void remove(Object o){
		if(o==null){
			for (int i = 0; i < elementData.length; i++) {
				if(elementData[i]==null){
					remove(i);
				}
			}
		}else{
			for (int i = 0; i < elementData.length; i++) {
				if(elementData[i]==o){
					remove(i);
				}
			}
		}
	}
	public int size(){
		return this.size;
	}
	public static void main(String[] args) {
		MyArrayList s=new MyArrayList();
		s.add(1);
		s.add(2);
		s.add(3);
		s.add(4);
		System.out.println("集合長度:"+s.size());
		s.remove(3);
		for (int i = 0; i < s.size(); i++) {
			System.out.println(s.get(i));
		}
	}
}
執行結果