自己模拟ArrayList:
private Object[] elementData; private int size; // 可以指定集合大小,默认10
public MyArrayList(int initialCapacity) {
if (initialCapacity < 0) {
try {
throw new IllegalArgumentException("Illegal Capacity: " + initialCapacity);
} catch (Exception e) {
e.printStackTrace();
}
}
elementData = new Object[initialCapacity];
} // 无参构造
public MyArrayList() {
this(10);
} // 返回集合大小
public int size() {
return size;
} // 返回集合大小
public boolean isEmpty() {
return size == 0;
} // 根据索引获取对象
public Object get(int index) {
rangeCheck(index);
return elementData[index];
} // 添加元素
public void add(Object object) {
ensureCapacity();
elementData[size++] = object;
} // 根据索引删除
public void remove(int index) {
rangeCheck(index);
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index + 1, elementData, index, numMoved);
elementData[--size] = null;
} // 根据对象删除
public void remove(Object object) {
for (int i = 0; i < size; i++) {
if (get(i).equals(object)) {
remove(i);
}
}
} // 替换
public Object set(int index, Object object) {
rangeCheck(index);
Object oldValue = elementData[index];
elementData[index] = object;
return oldValue;
} public void add(int index, Object obj) {
rangeCheck(index);
ensureCapacity(); // 数组扩容
System.arraycopy(elementData, index, elementData, index + 1, size - index);
elementData[index] = obj;
size++;
} // 数组扩容和数据的拷贝
private void ensureCapacity() {
if (size == elementData.length) {
Object newArray[] = new Object[size * 2 + 1];
System.arraycopy(elementData, 0, newArray, 0, elementData.length);
elementData = newArray;
}
} // 封装判断index是否合法
private void rangeCheck(int index) {
if (index >= size) {
try {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
} catch (Exception e) {
e.printStackTrace();
}
}
} public static void main(String[] args) {
MyArrayList list = new MyArrayList();
list.add("333");
list.add("444");
list.add("555");
list.add("344433");
list.add("222");
list.add("666");
list.remove("5");
list.set(0, "4432432");
list.add(5, "111");
System.out.println(list.size);
// System.out.println(list.get(6));
}