手动实现一个简单的ArrayList

时间:2021-04-25 06:32:11
import org.omg.CORBA.PUBLIC_MEMBER;

import java.io.Serializable;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;
import java.util.stream.Stream; public class MyArrayList<T> {
int size;
private Object array[];
private static final Object[] EMPTY_ARRAY={};
public MyArrayList()
{
this(10);
}
public MyArrayList(int initCapcity) {
if (initCapcity < 0)
throw new IllegalArgumentException("initCapcity必须大于0");
else if (initCapcity==0)
{
this.array=EMPTY_ARRAY;
}else {
array=new Object[initCapcity];
} }
public MyArrayList(Collection<? extends T> c)
{
array=c.toArray();
if((size=array.length)!=0)
{
if (array.getClass()!=Object[].class)
{
array=Arrays.copyOf(array,size,Object[].class);
}
}else {
this.array=EMPTY_ARRAY;
}
}
public boolean isEmpty()
{
return size==0;
} public int size() {
return size;
}
public boolean add(Object obj)
{
ensureCapacity();
array[size++]=obj;
return true;
}
public void add(int index,Object object)
{
rangeCheck(index);
ensureCapacity();
System.arraycopy(array,index,array,index+1,size-index);
array[index]=object;
size++; }
public Object remove(int index)
{
rangeCheck(index);
Object oldObject=array[index];
if (array.length-index-1>0)
{
System.arraycopy(array,index+1,array,index,array.length-index-1);
}
array[size--]=null;
return oldObject;
}
public boolean remove(Object object)
{
if (object==null)
{
for (int i=0;i<size;i++)
{
if (array[i]==null)
remove(i);
return true;
}
}else {
for (int i=0;i<size;i++)
{
if (object.equals(array[i]))
{
remove(i);
return true;
} }
}
return false;
} public Object get(int index)
{
rangeCheck(index);
return array[index];
}
public void set(int index,Object object)
{
rangeCheck(index);
Object oldObject=array[index];
array[index]=object;
}
//判断索引是否越界
public void rangeCheck(int index)
{
if (index>=size||index<0)
throw new IndexOutOfBoundsException("索引不在范围内");
} //数组容量与size相等时进行扩容
public void ensureCapacity()
{
if (size==array.length)
{
Object [] newArray=new Object[2*size+1];
System.arraycopy(array,0,newArray,0,array.length);
array=newArray;
}
}
}

测试类:

import java.util.ArrayList;

public class Demo1 {
public static void main(String[] args)
{
MyArrayList myArrayList=new MyArrayList<String>();
myArrayList.add("aaaaa");
myArrayList.add("bbbbb");
System.out.println(myArrayList.get(0));
System.out.println(myArrayList.get(1));
myArrayList.remove(0);
System.out.println(myArrayList.get(0));
myArrayList.set(0,"xujinfeng");
System.out.println(myArrayList.get(0));
System.out.println(myArrayList.size());
}
}

手动实现一个简单的ArrayList