ArrayList 底层实现的模拟实例
程序员文章站
2022-04-18 18:37:09
...
该实例模拟实现了底层ArrayList的添加,删除,获取对象,还有扩容等的实现方法。
package test;
import java.util.Date;
public class TestArrayList {
private Object[] elementData;
private int size; // 标记元素个数。默认值为0
public TestArrayList() {
this(10);
}
public TestArrayList(int initialCapacity) {
// 初始化定义数组的长度
if (initialCapacity > 0) {
elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
elementData = new Object[0];
} else {
try {
throw new Exception();
} catch (Exception e) {
e.printStackTrace();
}
}
}
// 向集合中添加元素
public void add(Object e) {
ensureCapacity();
elementData[size++] = e;
}
public Object get(int index) {
// 如果 index>=size 或者index<0, 就会抛出数组越界的异常。否则就返回元素。
rangeCheck(index);
return elementData[index];
}
public int size() {
return size;
}
// 判断集合是否为空
public boolean isEmpty() {
return size == 0;
}
private void rangeCheck(int index) {
if (index < 0 || index >= size) {
try {
throw new Exception();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public Object remove(int index) {
// 删除制定位置的元素:删除指定位置后,将后面的元素移动一位
// index的判断
rangeCheck(index);
Object value = elementData[index];
// 计算需要移动的对象个数
int numMoved = size - index - 1;
System.arraycopy(elementData, index + 1, elementData, index, numMoved);
elementData[--size] = null;
return value;
}
public boolean remove(Object data) {
boolean isRemoved = false;
for (int i = 0; i < size; i++) {
if (data.equals(get(i))) {
fastRemove(i);
isRemoved = true;
}
}
return isRemoved;
}
private void fastRemove(int index) {
int numMoved = size - index - 1;
System.arraycopy(elementData, index + 1, elementData, index, numMoved);
elementData[--size] = null;
}
public Object set(int index, Object obj) {
rangeCheck(index);
Object oldValue = elementData[index];
elementData[index] = obj;
return oldValue;
}
public void add(int index, Object obj) {
ensureCapacity();
System.arraycopy(elementData, index, elementData, index + 1, size - index);
elementData[index] = obj;
size++;
}
private void ensureCapacity() {
// 每次添加元素之前先要判断是否扩容
if (size == elementData.length) {
// 判断需要扩容,然后创建一个新的size*2+1 长度的数组。
Object[] newArray = new Object[size * 2 + 1];
// 将原数组的元素copy到新数组中。并将新数组对象赋值给引用变量elementData
System.arraycopy(elementData, 0, newArray, 0, elementData.length);
elementData = newArray;
}
}
public static void main(String[] args) {
TestArrayList l = new TestArrayList();
l.add(123); // 自动装箱成Integer对象
l.add("aaaaaa");
l.add(new Date());
l.add(44);
l.add(77);
System.out.println(l.size());
System.out.println(l.get(0));
System.out.println(l.remove(3));
System.out.println(l.get(3));
System.out.println(l.remove(new Integer(77)));
System.out.println(l.set(2, "123456"));
System.out.println(l.get(2));
l.add(1,20);
System.out.println(l.get(1));
}
}