package com.atgiugu.com;
import java.util.Arrays;
public class MyArrayList {
private Object[] data;
private int total;
public MyArrayList() {
data = new Object[5];
}
public void add(Object obj) {
CheckCapacityIsOutOfBounds();
data[total++] = obj;
}
protected void CheckCapacityIsOutOfBounds() {
if(total > data.length) {
data = Arrays.copyOf(data, data.length*2);
}
}
public int size() {
return total;
}
public int capacity() {
return data.length;
}
public Object get(int index) {
CheckIndexIsOutOfBounds(index);
return data[index];
}
public void set(int index, Object obj) {
CheckIndexIsOutOfBounds(index);
data[index] = obj;
}
protected void CheckIndexIsOutOfBounds(int index) {
if(index < 0 || index > total) {
throw new IndexOutOfBoundsException("下标越界");
}
}
public void insert(int index, Object value) {
CheckIndexIsOutOfBounds(index);
CheckCapacityIsOutOfBounds();
System.arraycopy(data, index, data, index+1, total-index);
data[index] = value;
total++;
}
public Object[] getAll() {
return Arrays.copyOf(data, total);
}
public void delete(int index) {
CheckIndexIsOutOfBounds(index);
System.arraycopy(data, index+1, data, index, total-index-1);
total--;
data[total] = null;
}
public int indexOf(Object value) {
if(value == null) {
for (int i = 0; i < total; i++) {
if(data[i] == null) {
return i;
}
}
}else {
for (int i = 0; i < total; i++) {
if(value.equals(data[i])) {
return i;
}
}
}
return -1;
}
public void delete(Object value) {
int index = indexOf(value);
if(index != -1) {
delete(index);
}
throw new RuntimeException("搜索元素不存在");
}
public void set(Object obj, Object value) {
int index = indexOf(obj);
set(index, value);
throw new RuntimeException("没有找到被替换元素");
}
}
package com.atgiugu.com;
import java.util.Arrays;
public class TestMyArrayList {
public static void main(String[] args) {
MyArrayList m = new MyArrayList();
m.add("张三");
m.add("李四");
m.add("王五");
Object[] all = m.getAll();
for(int i=0; i < all.length; i++) {
System.out.println(all[i]);
}
}
}