首页 > 代码库 > JAVA学习笔记-模拟ArrayList容器的底层实现

JAVA学习笔记-模拟ArrayList容器的底层实现

package MyArrayList;
import java.util.*;
/**
* 模拟实现JDK中的ArrayList类
* @author iwang
*
*/
public class MyArrayList {
/**
* The value is used for Object storage.
*/
  private Object[] value;

/**
* The size is the number of Object used.
*/
  private int size;

  public void rangeCheck(){
    try {
      throw new Exception();
      } catch (Exception e) {
// TODO Auto-generated catch block
      e.printStackTrace();
  }
}

public Object set(int index,Object obj){
  rangeCheck();
  Object old = value[index];
  value[index] = obj;
  return old;
}

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 int size(){
  return size;
}
public boolean isEmpty() {
  return size == 0;
}

public MyArrayList(){
//value = http://www.mamicode.com/new Object[10];
  this(10);
}
public MyArrayList(int size){
  if(size<0){
  rangeCheck();
  }
  value = http://www.mamicode.com/new Object[size];
}
public void inPut(Object obj){
  value[size] = obj;
  size++;
  if(size>value.length-1){
    int Capacity = (value.length << 1)+ 2;
    Object[] newlist = new Object[Capacity];
    for(int i=0;i<value.length;i++){
      newlist[i] = value[i];
    }
    value = http://www.mamicode.com/newlist;
  }
}
public Object getvalue(int index){
  if(index<0||index>size-1){
    rangeCheck();
  }
  return value[index];
}
public static void main(String[] args){
  MyArrayList a = new MyArrayList(2);
  a.inPut("abcd");
  a.inPut(new Human("IS ME"));

  a.inPut("123456");
  a.inPut("123456");
  a.inPut("123456");
  a.inPut("123456");
  a.inPut("123456");

  Human me = (Human)a.getvalue(1);
  System.out.println(me.getName());

  System.out.println(a.size());

  System.out.println(a.indexOf("abcd"));
  System.out.println(a.lastIndexOf("abcd"));

}
}

 

package MyArrayList;

public class Human {
  private String name;
  public Human(String name){
    this.name = name;
  }
  public String getName(){
    return this.name;
  }
  public void setName(String name){
  this.name = name;
  }
}

JAVA学习笔记-模拟ArrayList容器的底层实现