自定義數組

package com.xp.cn.study.struct;

public class Array<E> {

    private int size;

    private E[] data;

    public Array(int capacity) {
        data = (E[]) new Object[capacity];
        size = 0;
    }

    public Array() {
        this(10);
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public int getSize() {
        return this.size;
    }

    public void addLast(E e) {
        this.add(size, e);
    }

    public void addFirst(E e) {
        this.add(0, e);
    }


    public void add(int index, E e) {

        if (index < 0 || index > data.length - 1) {
            throw new IllegalArgumentException(" out of index ");
        }

        if (this.size == data.length) {
            throw new IllegalArgumentException(" data is full ");
        }

        for (int i = size + 1; i > index; i--) {
            data[i] = data[i - 1];
        }

        size++;
        data[index] = e;

    }


    public E remove(int index) {
        if (index < 0 || index > data.length - 1) {
            throw new IllegalArgumentException(" out of index ");
        }


        return null;

    }


    public E get(int index) {
        if (index < 0 || index > size) {
            throw new IllegalArgumentException(" out of index ");
        }
        return data[index];
    }


    @Override
    public String toString() {

        StringBuilder res = new StringBuilder();
        res.append(String.format("Array: size = %d , capacity = %d\n", size, data.length));
        res.append('[');
        for (int i = 0; i < size; i++) {
            res.append(data[i]);
            if (i != size - 1) {
                res.append(", ");
            }
        }
        res.append(']');
        return res.toString();
    }


    public static void main(String[] args) {
        Array<Integer> arr = new Array(20);
        for (int i = 0; i < 15; i++) {
            arr.add(i, i);
        }
        System.out.println(arr);

        arr.addFirst(-1);
        System.out.println(arr.toString());

        arr.add(0, 2);
        System.out.println(arr.toString());

        arr.add(2, 2);
        System.out.println(arr.toString());

        arr.addLast(15);
        System.out.println(arr);

        System.out.println(arr.get(0));
        System.out.println(arr.get(1));


        ClassLoader c = Array.class.getClassLoader();  //獲取Test類的類加載器

        System.out.println(c);

        ClassLoader c1 = c.getParent();  //獲取c這個類加載器的父類加載器

        System.out.println(c1);

        ClassLoader c2 = c1.getParent();//獲取c1這個類加載器的父類加載器

        System.out.println(c2);


    }

}
相關文章
相關標籤/搜索