ArrayList的简易实现
ArrayList 的部分方法:
方法的实现:
public class ArrayList {
private Object[] elementData;
private int size;
public int size(){
return size;
}
public boolean isEmpty(){
return size==0;
}
public ArrayList(){
elementData=new Object[10];
}
public ArrayList(int initalCapacity){
if(initalCapacity<0) {
try {
new Exception();
} catch (Exception e) {
e.printStackTrace();
}
}
this.size=initalCapacity;
elementData=new Object[initalCapacity];
}
public Object get(int index){
return elementData[index];
}
public Object set(int index,Object element){
if(index<0||index>size) {
try {
new Exception();
} catch (Exception e) {
e.printStackTrace();
}
}
Object oldValue=elementData[index];
elementData[index]=element;
return oldValue;
}
public void add(Object element){
if(size==elementData.length){
Object[] newArray=new Object[size*2+1];
System.arraycopy(elementData,0,newArray,0,elementData.length);
elementData=newArray;
}
elementData[size]=element;
size++;
}
public void add(int index,Object element){
if(index==size)
add(element);
if(index<0||index>size()) {
try {
new IndexOutOfBoundsException();
} catch (Exception e) {
e.printStackTrace();
}
}
if(size==elementData.length){
Object[] newArray=new Object[size*2+1];
System.arraycopy(elementData,0,newArray,0,elementData.length);
elementData=newArray;
}
for (int i = size; i >= index; i--) {
elementData[i + 1] = elementData[i];
}
elementData[index] = element;
}
public boolean remove(int index){
if(index>=0||index<size) {
for (int i = index + 1; i < size; i++) {
elementData[i] = elementData[i - 1];
}
elementData[size-1]=null;
return true;
}
return false;
}
public boolean remove(Object o){
for(int i=0;i<size;i++){
if(get(i).equals(o)){
remove(i);
return true;
}
}
return false;
}
public void clear(){
this.size=0;
}
}