arraylist是java中一个集合,它和linkedlist都为list子类
为了学习list于是自己写了一个简单的arraylist
因为arraylist的底层数组,所以和顺序表有几乎相同
package Array;
public class MyArrayList<T> {
private static final int DEFAULT_CAPACITY=10;
private int thesize;
private T[] theItems;
//构造方法
@SuppressWarnings("unchecked")
public MyArrayList(){
this.theItems=(T[]) new Object[DEFAULT_CAPACITY];
}
//定义初始长度的构造方法
@SuppressWarnings("unchecked")
public MyArrayList(int initialCapacity){
if(initialCapacity>0) {
this.theItems=(T[]) new Object[initialCapacity];
}else if(initialCapacity==0) {
this.thesize=0;
this.theItems=(T[]) new Object[DEFAULT_CAPACITY];
}else {
throw new IllegalArgumentException("输入有误 "+initialCapacity);
}
}
//添加指定元素指定元素
public boolean add(T newelement) {
if(thesize>theItems.length) {
grow();
}
theItems[thesize++]=newelement;
return true;
}
//扩容为原来得1.5
private void grow() {
int newTheSize=thesize+(thesize>>1);
T [] newTheTtems=(T[]) new Object[newTheSize];
for(int i=0;i<thesize;i++) {
newTheTtems[i]=theItems[i];
}
theItems=newTheTtems;
}
//获取指定位置数据
public T get(int index) {
if(index<0||index>=size()) {
throw new IllegalArgumentException("输入有误 "+index);
}
return this.theItems[index];
}
//将指定位置设置指定元素
public boolean set(int index ,T newT) {
if(index<0||index>=size()) {
throw new IllegalArgumentException("输入有误 "+index);
}
this.theItems[index]=newT;
return true;
}
//移除指定位置元素
public boolean remove(int index) {
if(index<0||index>=size()) {
throw new IllegalArgumentException("输入有误 "+index);
}
for(int i=index;i<thesize;i++) {
theItems[i-1]=theItems[i];
}
thesize--;
return true;
}
//移除所有元素
private void removeall() {
thesize=0;
}
//长度
public int size() {
return thesize;
}
//是否为空
public Boolean isEmpty() {
return size()==0;
}
}