根据JDK源码以及StingBuild相关知识,在这里用数组模拟一下ArrayList容器的底层实现。
package MyArraylist;
public class MyArrayList {
/**
* The value is used for object storage.
*/
private Object[] value;
/**
* The count is the number of object used.
*/
private int size;
/**
* 创建无参构造器
*/
public MyArrayList() {
this(16);
}
/**
* 重载
* @param size 数组长度
*/
public MyArrayList(int size) {
if(size < 0) {
try {
throw new Exception();
} catch (Exception e) {
e.printStackTrace();
}
}
value = new Object[size];
}
public int getSize() {
return size;
}
/**
* 添加数据
* @param obj 需要添加的对象
*/
public void add(Object obj) {
value[size] = obj;
size++;
//自动扩容功能
if(size>= value.length) {
int newsize = size*2+2;
Object[] newlist = new Object[newsize];
for(int i = 0;i<size;i++) {
newlist[i] = value[i];
}
value = newlist;
}
}
/**
* 取数据
* @param idx 需要取出的位置
* @return 取出的目标数据
*/
public Object get(int idx) {
if(rangeCheck(idx)==0) {
return value[idx];
}
return -1;
}
/**
* 判断空
* @return 是否为空
*/
public boolean isEmpyt() {
return size == 0;
}
/**
* 索引对象位置
* @param obj 需要索引的对象
* @return 对象的位置
*/
public int indexOf(Object obj) {
if(obj == null) {
return -1;
}else {
for(int i = 0;i<value.length;i++) {
if(obj == value[i]) {
return i;
}
}
}
return -1;
}
/**
* 反向索引
* @param obj 需要索引的对象
* @return 对象的位置
*/
public int lastIndexOf(Object obj) {
if(obj == null) {
return -1;
}else {
for(int i = size-1;i >= 0;i--) {
if(obj == value[i]) {
return i;
}
}
}
return -1;
}
/**
* 判断越界
* @param idx
*/
private int rangeCheck(int idx) {
if(idx<0||idx>size-1) {
//抛出异常
try {
throw new Exception();
} catch (Exception e) {
e.printStackTrace();
}
}
else {
return 0;
}
return 0;
}
/**
* 删除元素
* @param idx 需要删除位置的元素
* @return
*/
public Object deleteObjectAt(int idx) {
rangeCheck(idx);
System.arraycopy(value, idx+1, value, idx, size-idx-1);
size--;
return this;
}
}
下面我们再写一个类测试一下。
public class MyArrayListtest {
public static void main(String[] args) {
MyArrayList a = new MyArrayList(2);
a.add("第一个元素");
a.add("第二个元素");
a.add("第三个元素");
System.out.println(a.getSize());
System.out.println(a.get(1));
System.out.println(a.isEmpyt());
System.out.println(a.indexOf("第一个元素"));
System.out.println(a.lastIndexOf("第二个元素"));
System.out.println(a.deleteObjectAt(1));
}
}
/**
* output:
* 3
* 第二个元素
* false
* 0
* 1
* MyArraylist.MyArrayList@7852e922
*/