ArrayList自己实现(添加,插入,删除,遍历)

~~public class MyArrayList {

private Object[] elementData = {};
private int size = 0;

private void expand(){
	if( size == 0 ){
		elementData = new Object[10];
	}
	if( size == elementData.length ){	//扩容1.5倍
		elementData = Arrays.copyOf( elementData, size+(size>>1) );
	}
}

/**
 * 添加
 * @param e
 * @return
 */
public boolean add(E e){
	expand();
	elementData[size++]=e;
	return true;
}

/**
 * 插入
 * @param index
 * @param e
 * @return
 */
public boolean add( int index, E e ){
	if( index < 0 || index >= size ){	//数组下标越界
		throw new ArrayIndexOutOfBoundsException();
	}
	if( index == size ){
		return add(e);
	}
	expand();
	for(int i = size-1; i>=index; i--){
		elementData[i+1] = elementData[i];
	}
	elementData[index]=e;
	size++;
	return true;
}

/**
 * 删除
 */
public E remove(int index){
	if( index < 0 || index >= size ){	//数组下标越界
		throw new ArrayIndexOutOfBoundsException();
	}
	E e = (E) elementData[index];
	for( int i=index+1; i < size; i++ ){
		elementData[i-1] = elementData[i];
	}
	elementData[--size] = null;
	return e;
}

/**
 * toString()
 * @return 
 */
public String toString(){
	if( size == 0 ){
		return "[]";
	}
	StringBuilder stb = new StringBuilder();
	stb.append("[");
	stb.append(elementData[0]);
	for( int i = 1; i

}~~

你可能感兴趣的:(java基础)