zoukankan      html  css  js  c++  java
  • 自己实现一个ArrayList类

    package cn.hxd.collection;

    import java.util.ArrayList;
    import java.util.List;

    /**
    * 自己实现一个ArrayList
    * @author HXD
    *
    */
    public class ArrayList01 {
    private Object[] elementDate;
    private int size;

    public int size(){
    return size;
    }
    public boolean isEmpty(){
    return size == 0;
    }

    public ArrayList01(){
    this(10);
    }

    public ArrayList01(int initialCapacity){
    if(initialCapacity<0){
    try {
    throw new Exception();
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    elementDate = new Object[initialCapacity];
    }
    public void add(Object obj){
    ensureCapacity();//数组扩容
    elementDate[size++]=obj;
    // size++;
    }

    public void add(int index,Object obj){
    rangeCheck(index);
    ensureCapacity();//数组扩容
    System.arraycopy(elementDate, index, elementDate, index+1, size-index);
    elementDate[index] = obj;
    size++;
    }

    public Object get(int index){
    rangeCheck(index);
    return elementDate[index];
    }

    public void remove(int index){//删除指定位置的对象
    rangeCheck(index);
    int numMoved = size-index-1;//需要移动的对象个数
    if(numMoved>0){
    System.arraycopy(elementDate, index+1, elementDate, index, numMoved);
    }
    elementDate[--size]=null;
    }

    public void remove(Object obj){
    for(int i=0;i<size;i++){
    if(get(i).equals(obj)){
    remove(i);
    }
    }
    }

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


    private void ensureCapacity(){
    //数组扩容
    if(size==elementDate.length){
    Object[] newArray = new Object[size*2+1];
    //将原来数组里面的内容复制到新数组里面
    System.arraycopy(elementDate, 0, newArray, 0, elementDate.length);
    // for(int i=0;i<elementDate.length;i++){
    // newArray[i] = elementDate[i];
    // }
    elementDate = newArray;
    }
    }
    private void rangeCheck(int index){
    if(index<0||index>=size){
    try {
    throw new Exception();
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    }

    public static void main(String[] args) {
    ArrayList01 list = new ArrayList01(3);
    list.add("333");
    list.add("444");
    list.add("333");
    list.add("333");
    list.add("333");
    list.add("333");
    list.remove(2);
    System.out.println(list.size());
    System.out.println(list.get(1));

    }

    }

  • 相关阅读:
    子类调用父类被重写的方法
    Linux下编译出现undefined reference to ‘pthread_create’问题解决
    CRC校验8
    嵌入式C语言查表法
    Static关键字,遇到的问题_1
    java中方法的参数传递机制_一个对象被当作参数传递到一个方法后
    String使用equals和==比较的区别
    如何导入XML数据 (python3.6.6区别于python2 环境)
    0xx_PHP核心01
    PHP_MVC设计模式02
  • 原文地址:https://www.cnblogs.com/houxudong/p/7020722.html
Copyright © 2011-2022 走看看