ArrayList是以底层为数组的集合 要想实现实现首先要明白ArrayList 的两个问题
①:扩容
②:如何限制集合中添加的类型
下面是代码实现
package com.tb.bean;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
public class MyArrayList<E> {
// 底层数组
private E[] obj;
// 当前的大小
private int size;
// 容量
private int captial;
// 当到达容量后每次扩容递增的空间大小
private int limit;
public MyArrayList() {
// TODO Auto-generated constructor stub
this(5);
}
public MyArrayList(Collection<E> collection) {
int len = collection.size();
this.captial = len + 5;
Iterator<E> it = collection.iterator();
this.obj = (E[]) new Object[captial];
int i = 0;
while (it.hasNext()) {
Object object = it.next();
this.obj[i++] = (E) object;
}
this.size = len;
this.limit = 5;
}
public MyArrayList(int initnumber) {
this.captial = initnumber;
obj = (E[]) new Object[initnumber];
this.limit = 5;
}
public boolean isEmpty() {
return (size <= 0) ? true : false;
}
public int size(){
if(this.obj == null){
return -1;
}
return size;
}
public boolean add(E o) {
boolean flag = false;
if (this.obj == null) {
throw new NullPointerException();
}
if (o == null) {
return flag;
}
if (this.size >= this.captial) { //由于是线程不安全的 防止异步加载时出现问题
try {
E[] temp = (E[]) new Object[this.captial + this.limit]; //这个try catch 块主要是防止 开数组时内存爆满出现问题
System.arraycopy(this.obj, 0, temp, 0, this.captial);
this.obj = temp;
this.captial += limit;
} catch (Throwable t) { //可能是异常 也可能是error
throw new RuntimeException(t);
}
}
this.obj[size] = o;
this.size++;
flag = true;
return flag;
}
public E get(int i) {
if (i < 0 || i >= this.size) {
throw new IndexOutOfBoundsException("逻辑越界");
}
return this.obj[i];
}
public boolean remove(int i) {
boolean flag = true;
if (i < 0 || i >= this.size) {
throw new IndexOutOfBoundsException("逻辑越界");
}
try {
for (int j = i; this.obj[j]!=null && j < this.size - 1; j++) {
this.obj[j] = this.obj[j + 1];
}
this.size--;
if (this.captial - this.size >= this.limit) {
this.captial -= this.limit;
}
if (this.captial < 5) {
this.captial = 5;
}
E[] temp = (E[]) new Object[this.captial];
System.arraycopy(this.obj, 0, temp, 0, this.size);
this.obj = temp;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
flag = false;
}
return flag;
}
}
如有问题 欢迎指出