- 自己写一个简单的 ArrayList:
import java.util.Arrays;
/**
* Prudence 2019/6/21 16:27
*/
public class MyArrayList {
//Object可以接受任何子类的对象
private Object element[] = null;//默认就是null
//提供一个属性可以统计当前数组中存储元素的个数
private int size = 0;
//在创建空的AraryList时,默认会创建一个大小为10的数组
private static final int DEFAULT_INIT_CAPACITY = 10;
public MyArrayList() {
this(10);
}
public MyArrayList(int initCapacity) {
if(initCapacity < 0){
//参数异常
throw new IllegalArgumentException("容量不能为0");
}
element = new Object[initCapacity];
}
//向集合中添加元素
public void add(Object ele){
//需要判断集合大小从而扩容
if(size == element.length){
//进行扩容
Object[] temp = Arrays.copyOf(element, element.length * 2);
//将新数组的引用,给原有数组
element = temp;
}
//添加元素
element[size] = ele;
size++;
}
//获取集合中的元素
public Object get(int index){
//判断下标
if(index < 0 || index >= size){
throw new ArrayIndexOutOfBoundsException("索引越界");
}
return element[index];
}
//设置指定下标位置的集合中的元素
public void set(int index,Object newEle){
//判断下标
if(index < 0 || index >= size){
throw new ArrayIndexOutOfBoundsException("索引越界");
}
element[index] = newEle;
}
//删除指定索引位置的元素
public void remove(int index){
//判断下标
if(index < 0 || index >= size){
throw new ArrayIndexOutOfBoundsException("索引越界");
}
for(int i = index; i < size - 1; i++){
//后一位向前一位移动
element[i] = element[i+1];
}
//把最后一位设置为null即可
element[size - 1] = null;
//把集合大小进行缩减
size--;
}
//ArrayList集合可以直接打印结果,因为重写了toString
@Override
public String toString() {
if(element == null){
return "null";
}
if(size == 0){
return "[]";
}
StringBuffer sbr = new StringBuffer();
sbr.append("[");
for (int index = 0; index < size; index++) {
sbr.append(element[index]);
if(index != size - 1){
sbr.append(",");
}else {
sbr.append("]");
}
}
return sbr.toString();
}
//返回集合中元素的个数
public int size(){
return size;
}
//判断集合中元素是否为空
public boolean isEmpty(){
return size == 0;
}
//清空集合
public void clear(){
this.element = new Object[DEFAULT_INIT_CAPACITY];
size = 0;
}
}