自己实现一个ArrayList类
package cn.hxd.collection;
import java.util.ArrayList;
import java.util.List;
/**
* 自己实现一个ArrayList
* @author HXD
*
*/
public class ArrayList01 {
private Object[] elementDate;
private int size;
public int size(){
return size;
}
public boolean isEmpty(){
return size == 0;
}
public ArrayList01(){
this(10);
}
public ArrayList01(int initialCapacity){
if(initialCapacity<0){
try {
throw new Exception();
} catch (Exception e) {
e.printStackTrace();
}
}
elementDate = new Object[initialCapacity];
}
public void add(Object obj){
ensureCapacity();//数组扩容
elementDate[size++]=obj;
// size++;
}
public void add(int index,Object obj){
rangeCheck(index);
ensureCapacity();//数组扩容
System.arraycopy(elementDate, index, elementDate, index+1, size-index);
elementDate[index] = obj;
size++;
}
public Object get(int index){
rangeCheck(index);
return elementDate[index];
}
public void remove(int index){//删除指定位置的对象
rangeCheck(index);
int numMoved = size-index-1;//需要移动的对象个数
if(numMoved>0){
System.arraycopy(elementDate, index+1, elementDate, index, numMoved);
}
elementDate[--size]=null;
}
public void remove(Object obj){
for(int i=0;i<size;i++){
if(get(i).equals(obj)){
remove(i);
}
}
}
public Object set(int index,Object obj){
rangeCheck(index);
Object oldValue = elementDate[index];
elementDate[index] = obj;
return oldValue;
}
private void ensureCapacity(){
//数组扩容
if(size==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;
}
}
private void rangeCheck(int index){
if(index<0||index>=size){
try {
throw new Exception();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
ArrayList01 list = new ArrayList01(3);
list.add("333");
list.add("444");
list.add("333");
list.add("333");
list.add("333");
list.add("333");
list.remove(2);
System.out.println(list.size());
System.out.println(list.get(1));
}
}