https://blog.csdn.net/kaikai_gege/article/details/105737631
/*手动实现ArrayList底层是用数组实现的存储。 特点:查询效率高,增删效率低,线程不安全。
* */
public class ArrayList<E>{
private Object[] elementData;
private int size;
private static final int DEFALT_CAPACITY = 10;//defalt_capacity
public ArrayList () {
elementData = new Object[DEFALT_CAPACITY];
}
public ArrayList(int s) {
if(s<0) {
throw new RuntimeException("建立失败");
}
else if (s == 0) {
elementData = new Object[DEFALT_CAPACITY];
}
else elementData =new Object[s];
}
public void add(E obj) {
if(size == elementData.length) {//就是将原来的数组拷贝到一个大数组里,然后再把大数组给原来数组。
Object [] a = new Object[elementData.length+(elementData.length>>1)]; //10 -> 10+10/2
//原数组为elementData, 从0 开始拷贝,拷贝到a数组里,从0位置开始放,拷贝elementData.length个
System.arraycopy(elementData, 0, a, 0, elementData.length);
elementData = a;
}
elementData[size++] = obj;
}
public E get(int index){
return (E) elementData[index];
}
public void set(E element, int index) {
if(index<0 || index >= size) {
throw new RuntimeException("索引不合法");
}
else elementData[index] = element;
}
public void remove(E element) {
for(int i =0;i<size ; i++) {
if(element.equals(get(i))) {
remove(i);
}
}
}
public void remove( int index) {
int numMove = size - index -1 ;
if(numMove >0) {
/* 从elementData中拷贝 ,从 index+1位置,拷贝到原数组里,放的位置是index,拷贝个数为 numMove个
比如 index = 2 ,size = 8 ,就是 8 -2 -1 = 5 拷贝 下标为3,4,5,6,7的数*/
System.arraycopy(elementData, index+1,elementData , index, numMove);
}
elementData[size -1] = null;
size--;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[");
for(int i =0;i<size;i++) {
sb.append(elementData[i]+",");//append可以用连接符号+
}
sb.setCharAt(sb.length()-1, ']');//在最后个位置换为括号
return sb.toString();//遍历数组
}
public int size () {
return size;
}
public boolean isEmpty() {
return size == 0 ? true : false;
}
public static void main(String[] args) {
ArrayList <Object> s1 = new ArrayList<>(20);
s1.add("aa");
s1.add("bb");
s1.add("cc");
System.out.println(s1.toString());
System.out.println(s1.size);
for(int j = 0; j<50;j++) {
s1.add("郭老"+j);
}
System.out.printf(s1.toString());
System.out.println();
s1.set("郭老大",51);
System.out.println(s1.get(51));
s1.remove("aa");
System.out.printf(s1.toString());
s1.remove(1);
System.out.println();
System.out.printf(s1.toString());
System.out.println();
System.out.println(s1.size == s1.elementData.length);
System.out.println(s1.size);
System.out.println(s1.elementData.length);//length 后面有空的单元
System.out.println(s1.isEmpty());
}
}