实现类似ArrayList的功能

 费德  2017/02/26 00:53  207 次

1.NewArrayList.java

package com.tiaozaoj;
import java.util.Arrays;

public class NewArrayList {
    private int size = 0;
    
    private Object[] elementData = new Object[100];
    
    //直接在后面添加
    public void add(Object o){
        //先判断该数组是否已满
        if(this.size == elementData.length){
            this.grow(elementData,5);
        }
        this.elementData[size] = o;
        this.size++;
    }
    
    private void grow(Object[] src,int length){
        this.elementData = Arrays.copyOf(src, src.length+length);
    }
    
    public void add(int index,Object o){
        this.verifyIndex(index);
        //先判断该数组是否已满
        if(this.size == elementData.length){
            this.grow(elementData,5);
        }
        for(int i=size;i>index;i--){
            this.elementData[i+1] = this.elementData[i];
        }
        this.elementData[index] = o;
        this.size++;
    }
    
    private void verifyIndex(int index){
        try{
            if(index <0 || index > this.size)
                throw new Exception("下标越界");
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    
    public Object get(int index){
        this.verifyIndex(index);
        return this.elementData[index];
    }
    
    public void remove(int index){
        this.verifyIndex(index);
        for(int i=index;i<size;i++){
            this.elementData[i] = this.elementData[i+1];
        }
        this.size--;
    }
    
    public int size(){
        return this.size;
    }
}

2.main.java

package com.tiaozaoj;

import java.util.Arrays;

public class main {
    public static void main(String[] args){
        NewArrayList  array = new NewArrayList();
        array.add("0");
        array.add("1");
        array.add("3");
        array.add("4");
        System.out.println(array.size());
        array.add(2,"2");
        array.remove(3);
    }
}

 作者:费德

少年费德的奇幻漂流

本博客如无特殊说明皆为原创,转载请注明来源:实现类似ArrayList的功能

添加新评论