1. 程式人生 > >手動實現一個簡單的ArrayList

手動實現一個簡單的ArrayList

.get jin clas println ole ret pac argument 簡單的

import org.omg.CORBA.PUBLIC_MEMBER;

import java.io.Serializable;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;
import java.util.stream.Stream;

public class MyArrayList<T> {
    int size;
    
private Object array[]; private static final Object[] EMPTY_ARRAY={}; public MyArrayList() { this(10); } public MyArrayList(int initCapcity) { if (initCapcity < 0) throw new IllegalArgumentException("initCapcity必須大於0"); else if (initCapcity==0) {
this.array=EMPTY_ARRAY; }else { array=new Object[initCapcity]; } } public MyArrayList(Collection<? extends T> c) { array=c.toArray(); if((size=array.length)!=0) { if (array.getClass()!=Object[].class) { array
=Arrays.copyOf(array,size,Object[].class); } }else { this.array=EMPTY_ARRAY; } } public boolean isEmpty() { return size==0; } public int size() { return size; } public boolean add(Object obj) { ensureCapacity(); array[size++]=obj; return true; } public void add(int index,Object object) { rangeCheck(index); ensureCapacity(); System.arraycopy(array,index,array,index+1,size-index); array[index]=object; size++; } public Object remove(int index) { rangeCheck(index); Object oldObject=array[index]; if (array.length-index-1>0) { System.arraycopy(array,index+1,array,index,array.length-index-1); } array[size--]=null; return oldObject; } public boolean remove(Object object) { if (object==null) { for (int i=0;i<size;i++) { if (array[i]==null) remove(i); return true; } }else { for (int i=0;i<size;i++) { if (object.equals(array[i])) { remove(i); return true; } } } return false; } public Object get(int index) { rangeCheck(index); return array[index]; } public void set(int index,Object object) { rangeCheck(index); Object oldObject=array[index]; array[index]=object; } //判斷索引是否越界 public void rangeCheck(int index) { if (index>=size||index<0) throw new IndexOutOfBoundsException("索引不在範圍內"); } //數組容量與size相等時進行擴容 public void ensureCapacity() { if (size==array.length) { Object [] newArray=new Object[2*size+1]; System.arraycopy(array,0,newArray,0,array.length); array=newArray; } } }

測試類:

import java.util.ArrayList;

public class Demo1 {
    public static void main(String[] args)
    {
        MyArrayList myArrayList=new MyArrayList<String>();
        myArrayList.add("aaaaa");
        myArrayList.add("bbbbb");
        System.out.println(myArrayList.get(0));
        System.out.println(myArrayList.get(1));
        myArrayList.remove(0);
        System.out.println(myArrayList.get(0));
        myArrayList.set(0,"xujinfeng");
        System.out.println(myArrayList.get(0));
        System.out.println(myArrayList.size());
    }
}

技術分享圖片

手動實現一個簡單的ArrayList