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

Posted iamAnonymous

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 = 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容器的底层实现的主要内容,如果未能解决你的问题,请参考以下文章

java学习笔记--类ArrayList和LinkedList的实现

Java基础学习数据结构

JAVA编程思想(第四版)学习笔记----11.4 容器的打印

Java ArrayList源码剖析

Java学习笔记:List,Set,Map

Java ArrayList源码分析