Java面试题之手写ArrayList

package com.xingtu.sdk.sdk;

public class MyArrayList<T> {

    private T[] array;
    private int theSize;

    public MyArrayList(){
        this(10);
    }

    private MyArrayList(int length){
        try {
            new Exception();
        }catch (Exception e){
            e.printStackTrace();
        }
        array = (T[]) new Object[length];
    }

    /**
     * 添加元素
     * @param t
     * @return
     */
    public boolean add(T t){
        add(size(),t);
        return true;
    }

    /**
     * 在对应位置添加元素
     * @param idx
     * @param t
     */
    private void add(int idx,T t){
        if (array.length == size()){
            //扩容
            ensureCapacity(size() * 2 + 1);
        }
        if (idx > size())
            idx = size();

        array[idx] = t;
        if (idx >= size()) {
            theSize++;
        }
    }

    /**
     * List扩容
     * @param newSize
     */
    private void ensureCapacity(int newSize){
        if (newSize < size()){
            return;
        }
        T[] ot = array;
        array = (T[]) new Object[newSize];
        for (int i = 0;i < ot.length;i++){
            array[i] = ot[i];
        }
    }

    /**
     * 移除元素
     * @param idx
     * @return
     */
    public T reomve(int idx){
        T removedItem = array[idx];
        for(int i = idx; i < size()-1; i++){ //为什么不是size()
            array[i] = array[i + 1];
        }
        theSize--;
        return removedItem;
    }

    /**
     * 设置某位置元素
     * @param idx
     * @param newVal
     * @return
     */
    public T set(int idx,T newVal){
        if(idx < 0 || idx >= size()){
            return null;
        }else{
            T old = array[idx];
            array[idx] = newVal;
            return old;
        }
    }

    /**
     * 获取List长度
     * @return
     */
    public int size(){
        return theSize;
    }

    /**
     * 判断List是否为空
     * @return
     */
    public boolean isEmpty(){
        return size() == 0;
    }

    /**
     * 获取对应下标元素
     * @param idx
     * @return
     */
    public T get(int idx){
        if(idx < 0 || idx >= size()){
            return null;
        }else{
            return array[idx];
        }
    }

    public static void main(String[] args){
        MyArrayList<String> list = new MyArrayList<>();
        int size = list.size();
        System.out.println("size1 = "+ size);
        list.add("1");
        list.add("2");
        list.add("3");
        System.out.println("size2 = "+ list.size());
        list.reomve(0);
        System.out.println("size3 = "+ list.size());
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值