public class SxtArrayList<E>{
private Object[] elementData;
private int size;
private static final int Defalut_Capacity = 10;
public SxtArrayList() {
elementData = new Object[Defalut_Capacity];
}
public SxtArrayList(int Capacity) {
elementData = new Object[Capacity];
}
public void add(E element) {//添加元素
if (size == elementData.length) {
Object[] newArray = new Object[elementData.length + (elementData.length>>1)];
System.arraycopy(elementData, 0, newArray, 0, elementData.length);
elementData = newArray;
}
elementData[size++] = element;
}
public E get(int index) {//输入索引返回元素
return (E)elementData[index];
}
public void set(E element,int index) {//在某个索引设置元素
checkIndexRange(index);
elementData[index] = element;
}
public void checkIndexRange(int index) {//检查索引有没有超过size
if(index < 0 || index > size - 1) {
throw new RuntimeException("索引不合法:" + index);
}
}
@Override
public String toString() {//重写toString函数
StringBuilder sb = new StringBuilder();
sb.append("[");
for (int i = 0; i < size; i++) {
sb.append(elementData[i]+",");
}
sb.setCharAt(sb.length() - 1, ']');
return sb.toString();
}
public void remove(E element) {//删除元素
for (int i = 0; i < elementData.length; i++) {
if(element.equals(get(i))) {
remove(i);
}
}
}
public void remove(int index) {//通过索引删除元素
int moveNum = elementData.length - index - 1;
if (moveNum > 0) {
System.arraycopy(elementData, index + 1, elementData, index, moveNum);
}
elementData[--size] = null;
}
public int size() {//数组的大小
return size;
}
public static void main(String[] args) {
SxtArrayList s1 = new SxtArrayList();
for (int i = 0; i < 40; i++) {
s1.add("shan" + i);
}
s1.remove("shan3");
System.out.println(s1);
System.out.println(s1.size());
}
}