Imitating JDK to write a simple ArrayList -- the ArrayList of Gao Qi's Java 300 notes

Recently, I watched the video of Gao Qi's 300 lectures. I have seen the first 100 episodes. It's time to take notes.

ArrayList is a subclass of List. It has order and can be repeated. The underlying implementation is array, thread is not safe and efficient. Fast query, slow modification, insertion and deletion.

The following code simply implements the add(), set(), isEmpty(), remove(), get(), size() and other methods of ArrayList. The static method arraycopy of java.lang.System class is used to move the elements in the array, and the array copy is used.

Let's put the code directly.

package cn.bjsxt.collection;

import java.util.Date;

/**
 * Implement an ArrayList by yourself
 * @author
 *
 */
public class SxtArrayList /*implements List*/ {
    
    private Object[] elementData;  //An array of objects
    
    private int size;  //ArrayList Size of
    
    //Return ArrayList Size of
    public int size() {
        return size;
    }
    
    //ArrayList Empty or not
    public boolean isEmpty() {
        return size == 0;
    }
    
    //Parameterless constructor
    public SxtArrayList() {
        this(10);  //The default container size is 10
    }
    
    //Constructor Overload 
    public SxtArrayList(int initialCapacity) {
        if(initialCapacity<0) {
            try {
                throw new Exception();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        elementData = new Object[initialCapacity];
    }
    
    //Append an object
    public void add(Object obj) {
        ensureCapacity();  //Array expansion
        elementData[size++] = obj;
    }
    
    //Inserts an object at the specified location
    public void add(int index, Object obj) {
        rangeCheck(index);
        
        ensureCapacity();  //Array expansion
        
        //Move the array one bit back from the specified position
        System.arraycopy(elementData, index, elementData, index+1, size-index);
        elementData[index] = obj;
        size++;
    }
    
    //Get the element at the specified location
    public Object get(int index) {
        rangeCheck(index);  //Check array out of bounds
        return elementData[index];
    }
    
    //Delete object at specified location
    public void remove(int index) {
        rangeCheck(index);  //Check array out of bounds
        int numMoved = size - index - 1;  //The length of the element to be moved
        if(numMoved > 0) {
            //Move the element after the specified position forward one bit by copying the array
            System.arraycopy(elementData, index+1, elementData, index, numMoved);
        }
        elementData[--size] = null;  //Make the last element of the array null
    }
    
    //remove Overload of
    public void remove(Object obj) {
        for(int i=0;i<size;i++) {
            if(get(i).equals(obj)) {  //Note: the underlying call is equals Method, not==
                remove(i);
                
            }
        }
    }
    
    //Replace an element at a location and return the replaced object
    public Object set(int index, Object obj) {
        rangeCheck(index);
        
        Object oldValue = elementData[index];
        elementData[index] = obj;
        return oldValue;
    }
    
    private void ensureCapacity() {
        //Array expansion and data copy
        if(size == elementData.length) {
            Object[] newArray = new Object[size*2 + 1];  //Create a new array, the length is 2 times of the original plus 1
            
            System.arraycopy(elementData, 0, newArray, 0, elementData.length);  //Copy the elements in the old array to the new array
            elementData = newArray;
            
        }
    }
    
    //Check whether the array is out of bounds
    private void rangeCheck(int index) {
        if(index<0 || index>=size) {
            try {
                throw new Exception();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    public static void main(String[] args) {
        SxtArrayList list = new SxtArrayList(3);
        list.add("aaa");
        list.add("aaa");
        list.add("444");
        list.add(new Date());
        System.out.println(list.isEmpty());
        System.out.println(list.size());
        System.out.println(list.get(3));
        System.out.println("The replaced elements are:" + list.set(3, "345"));
        System.out.println("The replaced elements are:" + list.get(3));
        list.add(2,"abc");
        System.out.println(list.get(2));
        
        list.remove(2);
        System.out.println("####################################");
        for(int i=0;i<list.size();i++) {
            System.out.println(list.get(i));
        }
        list.remove("aaa");
        System.out.println("####################################");
        for(int i=0;i<list.size();i++) {
            System.out.println(list.get(i));
        }
        
    
    }
    
}

Tags: Java

Posted on Sun, 03 May 2020 16:40:57 -0400 by matt_wood87