第59集:数组模拟ArrayList容器的底层实现JDK源码分析ArrayList
本节课高老师带着我们模拟了一遍如何从0开始写一个类。
package com.test059;
public class MyArrayList {
private Object[] value;
private int size;
public MyArrayList(){
// value = new Object[16];
this(10);
}
public MyArrayList(int size){
if(size<0){
//抛异常
}
value = new Object[size];
}
public int indexOf(Object obj){
if(obj==null){
return -1;
} else {
for(int i = 0;i<value.length;i++){
if(obj==value[i]){
return i;//找到就结束循环了
}
}
return -1;
}
}
public int lastIndexOf(Object obj){
if(obj == null){
return -1;
} else {
for(int i = value.length - 1;i >= 0; i--){
if(obj == value[i]){
return i;//找到就结束循环
}
}
}
return -1;
}
public void add(Object obj){
value[size] = obj;
size++;
if(size >= value.length){
//装不下,需要扩容
int newCapacity = value.length*2;
Object[] newList = new Object[newCapacity];// 创建新对象
//将老对象的内容复制到新的对象。
for(int i = 0;i<value.length;i++){
newList[i] = value[i];
}
value = newList;
}
}
public int size(){
return size;
}
public Object get(int index){
return value[index];
}
public Object set(int index,Object object){
rangeCheck(index);
Object old = value[index];
value[index] = object;
return old;
}
public void rangeCheck(int index){
if(index<0||index>size-1){//[0,size-1]
try{
throw new Exception();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public int getSize() {
return size;
}
public static void main(String[] args){
MyArrayList list = new MyArrayList();
list.add("aaa");
list.add(new Human("王涛"));
list.add("bbb");
// for(int i = 0;i < 16;i++){
// System.out.println(list.value[i]);
// }
Human h = (Human)list.value[1];//
System.out.println(h.getName());
//System.out.println(((Human)list.value[1]).getName());
}
}