package com.hong.list;
public class ArrayList {
private Object[] elementData;
private int size;
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
public ArrayList() {
this(10);
}
public ArrayList(int initialCapacity) {
if (initialCapacity < 0) {
try {
throw new Exception();
} catch (Exception e) {
e.printStackTrace();
}
}
elementData = new Object[initialCapacity];
}
public void add(Object obj) {
// 数组扩容
if (size == elementData.length) {
Object[] newArray = new Object[size * 2 + 1];
System.arraycopy(elementData, 0, newArray, 0, elementData.length);
/*
* for (int i = 0; i < elementData.length; i++) {
* newArray[i]=elementData[i]; }
*/
elementData = newArray;
}
elementData[size++] = obj;
// size++;
}
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);
/*
* for (int i = 0; i < elementData.length; i++) {
* newArray[i]=elementData[i]; }
*/
elementData = newArray;
}
}
public Object get(int index) {
rangeCheck(index);
return elementData[index];
}
public void remove(int index) {
rangeCheck(index);
// 删除指定位置的对象
// a b c d e
if (index < 0 || index >= size) {
try {
throw new Exception();
} catch (Exception e) {
e.printStackTrace();
}
int numMoved = size - index - 1;
if (numMoved > 0) {
System.arraycopy(elementData, index + 1, elementData, index, numMoved);
}
elementData[--size] = null;
}
}
public void remove(Object obj) {
for (int i = 0; i < size; i++) {
if (get(i).equals(obj)) {// 注意:底层调用的equals方法,不是==;
remove(i);
}
}
}
public Object set(int index, Object obj) {
rangeCheck(index);
Object oldValue = elementData[index];
elementData[index] = obj;
return oldValue;
}
private void rangeCheck(int index) {
if (index < 0 || index >= size) {
try {
throw new Exception();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
ArrayList slist = new ArrayList(3);
slist.add(132);
slist.add("444");
slist.add(5);
slist.add("333");
slist.add("333");
slist.add("abc");
slist.add("ccc");
System.out.println(slist.size);
System.out.println(slist.get(6));
}
}