@org.junit.Test
public void test(){
//1.创建一个容器
MyArrayList list = new MyArrayList();
//2.装对象
list.add("张三");
list.add("李四");
list.add("王五");
list.add(null); //null也合法
list.add(10);
//3.查看有几个元素
System.out.println(list.size());
System.out.println();
//4.遍历元素
Object[] objects = list.toArray();
for (int i = 0; i < objects.length; i++) {
System.out.println(objects[i]);
}
System.out.println();
//5.获取index位置的元素
Object object = list.get(0);
System.out.println(object);
System.out.println();
//6.查询李四的位置
int index = list.indexOf("李四");
System.out.println(index);
System.out.println();
//7.替换“李四”为“张康”
Object[] newObjects = list.set("李四", "张康");
for (int i = 0; i < newObjects.length; i++) {
System.out.println(newObjects[i]);
}
}
public class MyArrayList{
private Object[] data;
private int total;
public MyArrayList() {
this.data = new Object[10]; //默认初始化大小
}
//添加元素
public void add(Object obj){
//是否已满
if(total >= data.length)
//扩容
data = Arrays.copyOf(data, data.length*2);
data[total++] = obj;
}
//获取有效元素的个数
public int size(){
return total;
}
//把数据用数组返回
public Object[] toArray(){
return Arrays.copyOf(data, total);
}
//获取index位置的元素
public Object get(int index){
if (index < 0 || index >= total)
throw new IndexOutOfBoundsException(index + "不合法");
return data[index];
}
//查找obj在当前容器中的索引,如果没有,返回-1
public int indexOf(Object obj){
int index = -1;
//null.equals("")会报空指针异常
//"".equals(null)不会报空指针异常
if (obj == null) {
for (int i = 0; i < total; i++){
if (obj == data[i]) {
index = i;
break;
}
}
} else {
for (int i = 0; i < total; i++){
if (obj.equals(data[i]) ) {
index = i;
break;
}
}
}
return index;
}
//删除对象
public void remove(Object obj) {
//(1)找到obj位置
int index = indexOf(obj);
//(2)删除
if (index != -1) {
System.arraycopy(data, index+1, data, index, total-index-1);
data[--total] = null;
}
}
//把容器中的old替换成dest
public Object[] set(Object old, Object dest) {
int index = indexOf(old);
if (index != -1)
data[index] = dest;
return Arrays.copyOf(data, total);
}
}