ArrayList(模拟底层数组实现,手写)

package com.yidu.demo;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Vector;

import org.omg.Messaging.SyncScopeHelper;
/**
 * 模拟数组集合(底层数组实现)
 * @author Administrator
 */
public class Array{
    private Object[] elementsData;
    private int size;
    //构造方法,初始化数组
    public Array(){
        this(10);
    }
    public Array(int initialCapacity){
        if(initialCapacity<1){
            try {
                throw new Exception();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        elementsData=new Object[initialCapacity];
    }
    public void add(Object obj){
        //数组扩容
        ensureCapacityInternal();
        elementsData[size++]=obj;
        
    }
    public void add(int index,Object obj){
        rangeCheck(index);
        //数组扩容
        ensureCapacityInternal();
        System.arraycopy(elementsData, index, elementsData, index+1, size-index);
        elementsData[index]=obj;
        size++;
        
    }
    public Object get(int index){
        rangeCheck(index);
        return elementsData[index];
    }
    public void remove(int index){
        rangeCheck(index);
        System.arraycopy(elementsData, index+1, elementsData, index, size-index-1);
        elementsData[--size]=null;
    }
    public void remove(Object obj){
        if(obj==null){
            for (int i = 0; i < elementsData.length; i++) {
                if(elementsData[i]==obj){
                    System.arraycopy(elementsData, i+1, elementsData, i, size-i-1);
                    elementsData[--size]=null;
                    break;
                }
            }
        }else{
            for (int i = 0; i < elementsData.length; i++) {
                if(elementsData[i].equals(obj)){
                    System.arraycopy(elementsData, i+1, elementsData, i, size-i-1);
                    elementsData[--size]=null;
                    break;
                }
            }
        }
    }
    public void set(int index,Object obj){
        rangeCheck(index);
        elementsData[index]=obj;
    }
    private void rangeCheck(int index){
        if(index>=size||index<0){
            try {
                throw new Exception();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    private void ensureCapacityInternal(){
        if(size==elementsData.length){
            Object[] newArr=new Object[size*2];
            //将旧数组拷贝到新数组
            System.arraycopy(elementsData, 0, newArr, 0, elementsData.length);
            elementsData=newArr;
        }
    }
    public static void main(String[] args) {
        Array a=new Array();
        for (int i = 0; i < 21; i++) {
            a.add(i);
        }
        System.out.println(a.size);
    }
}

你可能感兴趣的:(ArrayList(模拟底层数组实现,手写))