/*1、使用数组模拟实现java中的ArrayList,模仿StringBuilder
*2、对java中的ArrayList的底层实现进行分析
*/
public class MyArrayList {
//The value is used for Object storage.
private Object[] value;
//The size is the number of Objects used.
private int size;
//Two Constructors.default:size=16; DIY:input size.
public MyArrayList() {
this(16);
}
public MyArrayList(int size) {
if(size<0){
try {
throw new Exception();
}
catch (Exception e) {
e.printStackTrace();
}
}
value = new Object[size];
}
//method_one: add, the method of adding an object to the "MyArrayList".
public void add(Object obj){
value[size] = obj;
size++;
//if old one is too small.
if(size>=value.length){
int newCapacity = value.length*2;
Object[] newList = new Object[newCapacity];
//copy from old small "MyArrayList".
// System.arraycopy(src, srcPos, dest, destPos, length);
for(int i=0;i<value.length;i++){
newList[i] = value[i];
}
value = newList;
}
}
//method_two: get, the method of getting an object from the "MyArrayList".
//You must input an element's index you want.
public Object get(int index){
//if IndexOutOfBoundsException occurred.
if(index<0||index>size-1){
try {
throw new Exception();
}
catch (Exception e) {
e.printStackTrace();
}
}
return value[index];
}
//method_three: size, the method of getting length of "MyArrayList".
public int size(){
return size;
}
}