码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2016-11-12 16:16:03      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:stack   port   private   capacity   ted   exception   pack   storage   --   

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 = new Object[10];
  this(10);
}
public MyArrayList(int size){
  if(size<0){
  rangeCheck();
  }
  value = 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 = 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容器的底层实现

标签:stack   port   private   capacity   ted   exception   pack   storage   --   

原文地址:http://www.cnblogs.com/iamAnonymous/p/6056578.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!