随笔
自定义一个简单的arraylist
public class sxtArrayList<E> {
private Object[] elementDate;
private int size;
private static final int DEFAULT_CAPACITY = 10;
public sxtArrayList() {
elementDate = new Object[DEFAULT_CAPACITY];
}
public sxtArrayList(int ca) {
elementDate = new Object[ca];
}
public void add(E element) {
//什么时候扩容
if(size == elementDate.length) {
//怎么扩容
Object[] newArray = new Object[elementDate.length+(elementDate.length<<1)] ;
System.arraycopy(elementDate, 0, newArray, 0, elementDate.length);
elementDate = newArray;
}
elementDate[size++]= element;
}
public E get(int i) {
jianchashuzu(i);
return (E)elementDate[i];
}
public void set(E element,int indx) {
jianchashuzu(indx);
elementDate[indx] = element;
}
public void jianchashuzu(int indx) {
//判断索引是否合法【0,size)
if(indx<0||indx>=size) {
//该索引不合法
throw new RuntimeException("索引不合法"+indx);
}
}
public void remove(E element) {
for(int i = 0 ;i<size;i++) {
if(element.equals(get(i))) {
//将该元素从此处移除
remove(i);
}
}
}
public void remove(int indx) {
int nummoved = elementDate.length-indx-1;
if(nummoved >0) {
System.arraycopy(elementDate, indx+1, elementDate, indx, nummoved);
}
elementDate[--size] = null;
}
@Override
public String toString() {
StringBuilder str = new StringBuilder();
//[打印]
str.append("[");
for(int i=0 ;i<size;i++) {
str.append(elementDate[i]+",");
}
str.setCharAt(str.length()-1, ']');
return str.toString();
}
public static void main(String[] args) {
sxtArrayList<String> ss= new sxtArrayList<>(30);
ss.add("aa");
ss.add("bb");
for(int i=0 ;i<40;i++){
ss.add("giao"+i);
}
System.out.println(ss);
ss.set("sdawdsad", 9);
ss.remove("bb");
System.out.println(ss);
}
}