2017년 4월 7일 금요일

ArrayList simple implementation

- java file

package org.blog.test;

public class TestApplication {
    public static void main(String[] args) {
        MyArrayList myArrayList = new MyArrayList();
        myArrayList.add("sdfd");
        myArrayList.add("sdfd1");
        myArrayList.add("sdfd2");
        myArrayList.remove(1);
        myArrayList.add(1, "sdfd1");
        myArrayList.add(1, "sdfd0.5");
        myArrayList.add(1, "sdfd0.3");
        myArrayList.remove(2);
        for (int i = 0; i < myArrayList.size(); i++) {
            System.out.println(myArrayList.get(i));
        }
        System.out.println(myArrayList.size());
    }
}

class MyArrayList {

    private int size;

    private Object[] data;

    public MyArrayList() {
        this.size = 0;
        this.data = new Object[100];
    }

    public void add(Object data) {
        this.data[this.size] = data;
        this.size++;
    }

    public void add(int index, Object data) {
        for (int i = this.size - 1; i >= index; i--) {
            this.data[i + 1] = this.data[i];
        }
        this.data[index] = data;
        this.size++;
    }

    public void remove(int index) {
        for (int i = index + 1; i <= this.size - 1; i++) {
            this.data[i - 1] = this.data[i];
        }
        this.data[this.size - 1] = -1;
        this.size--;
    }

    public Object get(int index) {
        return this.data[index];
    }

    public int size() {
        return this.size;
    }
}
- output
sdfd
sdfd0.3
sdfd1
sdfd2
4

Process finished with exit code 0

댓글 없음 :

댓글 쓰기