1. 程式人生 > >自己實現的帶泛型ArrayList

自己實現的帶泛型ArrayList

public class MyArrayList<T> {
	private Object[] arrayList;
	private int size;
	private int capacity;
	
	public MyArrayList() {
		this(10);
	}
	
	public MyArrayList(int capacity) {
		if(capacity <= 0) {
			throw new RuntimeException("必須大於0");
		}
		this.capacity = capacity;
		arrayList = new Object[capacity];
	}
	
	public int size() {
		return size;
	}
	
	public int capacity() {
		return capacity;
	}
	//線性表擴充
	public void extendsArrayList() {
		if(size >= capacity) {
			Object[] newArrayList = new Object[size * 2 + 1];
			this.capacity = size * 2 + 1;
			for(int i=0; i<size; i++) {
				newArrayList[i] = arrayList[i];
			}
			arrayList = newArrayList;
		}
	}
	
	//新增
	public boolean add(T obj) {
		extendsArrayList();
		arrayList[size] = obj;
		size++;
		return true;
	}
	
	//指定位置新增
	public boolean add(int index,T obj) {
		extendsArrayList();
		
		if(index < size && index >=0) {
			for(int i=size; i>=index; i--) {
				arrayList[i+1] = arrayList[i];
			}
			arrayList[index] = obj;
			size++;
			return true;
		} else if(index == size){
			add(obj);
			return true;
		} else {
			return false;
		}
	}
	
	//刪除
	public boolean remove(int index) {
		if(index < size) {
			for(int i=index; i<size -1; i++) {
				arrayList[i] = arrayList[i+1];
			}
			arrayList[size] = null;
			size--;
			return true;
		} else {
			return false;
		}
	}
	
	//刪除
	public boolean remove(T obj) {
		for(int i=0; i<size; i++) {
			if(arrayList[i].equals(obj)) {
				remove(i);
				break;
			}
		}
		
		return false;
	}
	
	//修改
	public boolean set(int index, T obj) {
		if(index < size) {
			arrayList[index] = obj;
			return true;
		} else {
			return false;
		}
	}
	
	//獲取
	public T get(int index) {
		if(index <size && index >=0) {
			return (T) arrayList[index];
		} else {
			throw new RuntimeException("陣列越界");
		}
	}
	
	//返回指定元素的位置
	public int indexOf(T obj) {
		
		for(int i=0; i<size; i++) {
			if(obj.equals(arrayList[i])) {
				return i;
			}
		}
		
		return -1;
	}
	
	//返回資料物件
	public Object[] toArray() {
		return arrayList;
	}
	
	//檢視是否包含
	public boolean contains(T obj) {
		for(int i=0; i<size; i++) {
			if(arrayList[i].equals(obj)) {
				return true;
			}
		}
		return false;
	}
}