自定义ArrayList(十八)

简介: 自定义ArrayList(十八)

一. 自定义ArrayList


ArrayList 位于 java.util 包下, 内部封装的是数组, 用于快速查询数据, 也支持添加,移除等操作。


由于是内部封装数组,数组复制操作很多,建议看一看上一章节的内容。


ArrayList 的源码非常好,建议多读一下。


老蝴蝶简单自定义一个 ArrayList, 实现相应的基础功能。


一.一 自定义 MyArrayList, 实现 ArrayList 功能


package com.yjl.collection;
import java.util.Arrays;
/**
 * package: com.yjl.collection
 * className: MyArrayList
 * Description: 用于实现 java.util.ArrayList 的集合功能
 *
 * @author : 两个蝴蝶飞
 * @Date :2020/6/10 12:47
 */
public class MyArrayList <E>{
    /**
     * 默认的长度是10
     */
    private final static int DEFAULT_CAPICATY=10;
    /**
     * 用数组进行集合
     */
    private Object[] elementData;
    /**
     * 目前存储的长度
     */
    private int size;
    /**
     * 空构造时,指定长度为默认的长度
     */
    public MyArrayList(){
       this(DEFAULT_CAPICATY);
    }
    /**
     * 传入长度
     * @param initCapicaty 初始化长度
     */
    public MyArrayList(int initCapicaty){
        if(initCapicaty<0){
            throw new RuntimeException("长度过小");
        }else if(initCapicaty==0){
            initCapicaty=DEFAULT_CAPICATY;
        }
        //初始化数组
        elementData=new Object[initCapicaty];
        //初始化长度
        size=0;
    }
    public MyArrayList(MyArrayList maList){
        //转换成数组
      Object[] obj=maList.toArray();
      elementData=obj;
      size=obj.length;
    }
    /**
     *
     * @return 返回长度
     */
    public int size(){
        return size;
    }
    /**
     *
     * @return 集合为空,返回true,不为空,返回false
     */
    public boolean isEmpty(){
        return size==0?true:false;
    }
    /**
     *
     * @param e 添加的元素
     * @return 添加单个集合
     */
    public boolean add(E e){
        //是否需要扩容
        beforeAddLength((size+(int)(size<<2)));
        //添加到末尾
         elementData[size++]=e;
         return true;
    }
    private void beforeAddLength(int maxLength){
        //如果添加到末尾了
        if(size==elementData.length){
            //扩展宽度
            Object[] copy=new Object[maxLength];
            //复制数组
            System.arraycopy(elementData,0,copy,0,size);
            //引用变换
            elementData=copy;
        }
    }
    /**
     *
     * @param index 索引
     * @param e 添加的元素
     */
    public void add(int index,E e){
        beforeAddLength((size+(int)(size<<2)));
        System.arraycopy(elementData,index,elementData,index+1,size-index);
        //当前位置 index 元素为 e
        elementData[index]=e;
        size++;
    }
    /**
     *
     * @param maList
     * @return 添加所有集合元素
     */
    public boolean addAll(MyArrayList maList){
        Object[] temp=maList.toArray();
        int newLength=temp.length;
        //长度大了,那么就扩展
        if(size+newLength>elementData.length){
            beforeAddLength(size+newLength);
        }
        System.arraycopy(temp,0,elementData,size,newLength);
        size=size+newLength;
        return true;
    }
    /**
     *
     * @param index 索引
     * @param maList 集合
     *
     */
    public void addAll(int index,MyArrayList maList){
        Object[] temp=maList.toArray();
        int newLength=temp.length;
        //长度大了,那么就扩展
        if(size+newLength>elementData.length){
            beforeAddLength(size+newLength);
        }
        if(index<size){
            //自身复制一下
            System.arraycopy(elementData,index,elementData,index+1,size-index);
        }
        System.arraycopy(temp,0,elementData,index,newLength);
        size=size+newLength;
    }
    /**
     * 清理
     */
    public void clear(){
        for(int i=0;i<elementData.length;i++){
            elementData[i]=null;
        }
        size=0;
    }
    /**
     * 克隆
     * @return
     */
    public MyArrayList clone(){
        try {
            MyArrayList<E> maList = (MyArrayList<E>) super.clone();
            maList.elementData=elementData;
            maList.size=size;
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     *
     * @param e
     * @return 是否包含某个对象
     */
    public boolean contains(Object e){
       return indexOf(e)>=0?true:false;
    }
    /**
     *
     * @param e 元素
     * @return 返回对象所在的位置,从前往后
     */
    public int indexOf(Object e){
        if(e==null){
            for(int i=0;i<size;i++){
                if(null==elementData[i]){
                    return i;
                }
            }
        }else{
            for(int i=0;i<size;i++){
                if(e.equals(elementData[i])){
                    return i;
                }
            }
        }
        return -1;
    }
    /**
     *
     * @param e
     * @return  返回对象所在的位置,从后往前
     */
    public int lastIndexOf(Object e){
        if(e==null){
            for(int i=size-1;i>=0;i--){
                if(null==elementData[i]){
                    return i;
                }
            }
        }else{
            for(int i=size-1;i>=0;i--){
                if(e.equals(elementData[i])){
                    return i;
                }
            }
        }
        return -1;
    }
    /**
     *
     * @param index
     * @param e
     * @return 设置值, 返回以前的老的值
     */
    public E set(int index,Object e){
        E old=get(index);
        elementData[index]=e;
        return old;
    }
    /**
     *
     * @param index
     * @return 获取某个索引的值
     */
    public E get(int index){
        if(index<0){
            throw new RuntimeException("索引错误");
        }else if(index>=size){
            throw new ArrayIndexOutOfBoundsException();
        }
        return (E)elementData[index];
    }
    /**
     *
     * @param index
     * @return 按照索引进行移除
     */
    public E remove(int index){
        if(index<0){
            throw new RuntimeException("索引错误");
        }else if(index>=size){
            throw new ArrayIndexOutOfBoundsException();
        }
        E old=get(index);
        System.arraycopy(elementData,index+1,elementData,index,(size-index-1));
        elementData[size--]=null;
        return old;
    }
    /**
     *
     * @param obj
     * @return 移除对象
     */
    public boolean remove(Object obj){
       int index= indexOf(obj);
        if(index>=0){
            System.arraycopy(elementData,index+1,elementData,index,(size-index-1));
            elementData[size--]=null;
            return true;
        }else{
            return false;
        }
    }
    /**
     * 转换成数组
     * @return
     */
    public Object[] toArray(){
        return  Arrays.copyOf(elementData,size);
    }
    /**
     *
     * @return 打印输出
     */
    public String toString(){
        StringBuilder sb=new StringBuilder();
        if(size==0){
            return "[]";
        }
        sb.append("[");
        for(int i=0;i<size;i++){
            sb.append(elementData[i]).append(",");
        }
        sb.replace(sb.length()-1,sb.length(),"]");
        return sb.toString();
    }
}


一.二 测试自定义 MyArrayList


package com.yjl.collection;
/**
 * package: com.yjl.collection
 * className: MyArrayListTest
 * Description: 请输入相应的描述
 *
 * @author : yuezl
 * @Date :2020/6/10 14:21
 */
public class MyArrayListTest {
    public static void main(String[] args) {
        MyArrayList<Integer> mal=new MyArrayList<Integer>();
        System.out.println("长度:"+mal.size()+",是否为空:"+mal.isEmpty());
        //添加元素
        mal.add(3);
        mal.add(4);
        //索引时添加
        mal.add(0,1);
        mal.add(1,2);
        //打印
        System.out.println("mal:"+mal.toString());
        //集合构建
        MyArrayList<Integer> mal2=new MyArrayList<Integer>(mal);
        System.out.println("mal2:"+mal2.toString());
        //添加所有
        mal2.addAll(mal);
        System.out.println("新的mal2:"+mal2.toString());
        //获取值
       Integer val= mal2.get(3);
        System.out.println("输出值为:"+val);
        //索引长度构造
        MyArrayList<Integer> mal3=new MyArrayList<Integer>(3);
        mal3.add(1);
        mal3.add(2);
        mal3.add(3);
        System.out.println("长度1:"+mal3.toArray().length);
        mal3.add(4);
        System.out.println("长度2:"+mal3.toArray().length);
        //移除
        mal3.remove(1);
        System.out.println("长度3:"+mal3.toArray().length);
        mal3.remove(new Integer(3));
        System.out.println("长度4:"+mal3.toArray().length);
        //清除
        mal3.clear();
        System.out.println("长度:"+mal3.size()+",是否为空:"+mal3.isEmpty());
    }
}


控制台打印输出:


20200610155235780.png


谢谢您的观看,如果喜欢,请关注我,再次感谢 !!!

相关文章
|
19天前
|
存储 Java API
JavaSE——常用API(3/3)-ArrayList入门、ArratList使用、ArrayList综合案例
JavaSE——常用API(3/3)-ArrayList入门、ArratList使用、ArrayList综合案例
23 0
|
6月前
|
存储 Java 索引
【零基础学Java】—ArrayList集合概述和基本使用(十四)
【零基础学Java】—ArrayList集合概述和基本使用(十四)
|
9月前
|
存储
自定义实现简易版ArrayList
自定义实现简易版ArrayList
35 0
|
11月前
|
存储 算法 Java
【JavaSE专栏46】Java常用类Arrays解析,原生数组和List集合有何区别?
【JavaSE专栏46】Java常用类Arrays解析,原生数组和List集合有何区别?
115 0
|
存储 C++ 容器
C++学习笔记(十六)——list
C++学习笔记(十六)——list
C++学习笔记(十六)——list
|
存储 C++ 容器
|
安全 Java
【蓝桥杯Java_C组·从零开始卷】第八节、集合——list详解(ArrayList、 LinkedList 和 Vector之间的区别)
【蓝桥杯Java_C组·从零开始卷】第八节、集合——list详解(ArrayList、 LinkedList 和 Vector之间的区别)
83 0
【蓝桥杯Java_C组·从零开始卷】第八节、集合——list详解(ArrayList、 LinkedList 和 Vector之间的区别)
|
存储 安全 Java
java学习之高级语法(十三)------ Map集合
java学习之高级语法(十三)------ Map集合
java学习之高级语法(十三)------ Map集合