public class WhArrayList<E> {
private Object[] elementData;
private int size;
private static final int DEFAUT_CAPACITY = 10;
public WhArrayList() {
elementData = new Object[DEFAUT_CAPACITY];
}
public WhArrayList(int capacity) {
if (capacity < 0) {
throw new RuntimeException("容量不可为负数!" + capacity);
} else if (capacity == 0) {
elementData = new Object[DEFAUT_CAPACITY];
} else if (capacity > 0) {
elementData = new Object[capacity];
}
}
public void add(E element) {
// 数组扩容
if (size == elementData.length) {
// 增大1/2 注意这里+号优先级更高,如果不加括号,会变为(10+10)/2,长度依然是10
Object[] newArray = new Object[elementData.length + (elementData.length >> 1)];
System.arraycopy(elementData, 0, newArray, 0, elementData.length);
// 指向新的数组对象
elementData = newArray;
}
elementData[size++] = element;
}
// 增加set和get方法
@SuppressWarnings("unchecked")
public E get(int index) {
checkRank(index);
return (E) elementData[index];
}
public void set(E element, int index) {
checkRank(index);
elementData[index] = element;
}
// 增加remove方法
public void remove(int index) {
checkRank(index);
int numMoved = elementData.length - index - 1;
if (numMoved > 0) {
System.arraycopy(elementData, index + 1, elementData, index, numMoved);
}
elementData[size - 1] = null;
size--;
}
public void remove(E element) {
// 挨个对比,获得第一个比较为true的
for (int i = 0; i < size; i++) {
if (element.equals(get(i))) {
remove(i);
}
}
}
// 判断索引是否合法,多处使用,形成公共方法
public void checkRank(int index) {
// 判断索引是否合法
if (index < 0 || index > size - 1) {
throw new RuntimeException("索引不合法:" + index);
}
}
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
@Override
public String toString() {
// 重写打印
StringBuilder sBuilder = new StringBuilder();
sBuilder.append("[");
for (int i = 0; i < size; i++) {
sBuilder.append(elementData[i] + ",");
}
sBuilder.setCharAt(sBuilder.length() - 1, ']');
return sBuilder.toString();
}
// 测试功能
public static void main(String[] args) {
WhArrayList<String> list1 = new WhArrayList<String>();
for (int i = 0; i <= 8; i++) {
list1.add("string" + i);
}
System.out.println(list1);
System.out.println(list1.get(6));
list1.set("hahahah", 6);
System.out.println(list1.get(6));
// list1.set("不合法的位置", 30);
System.out.println(list1);
list1.remove(2);
list1.remove("string4");
System.out.println(list1);
System.out.println(list1.size);
System.out.println(list1.isEmpty());
}
}