59_数组_模拟ArrayList容器的底层实现_JDK源码分析ArrayList

来源:互联网 发布:选择排序和冒泡算法 编辑:程序博客网 时间:2024/05/16 13:05
import java.util.ArrayList;public class MyArrayList {    private Object value[];    private int size;    public MyArrayList() {        // value = new Object[16];        this(2);    }    public MyArrayList(int size) {        value = new Object[size];    }    public void add(Object obj) {        value[size] = obj;        size++;        if (size >= value.length) {            // 装不下了,将要扩展容量了            int newCapacity = value.length * 2;            Object[] newList = new Object[newCapacity];            // System.arraycopy(src, srcPos, dest, destPos, length);            for (int i = 0; i < value.length; i++) {                newList[i] = value[i];            }            value = newList;        }    }    public int size() {        return size;    }    public boolean isEmpty() {        return size == 0;    }    public int indexOf(Object obj) {        if (obj == null) {            return -1;        } else {            for (int i = 0; i < value.length; i++) {                if (obj == value[i]) {                    return i;                }            }            return -1;        }    }    public int lastIndexOf(Object obj) {        if (obj == null) {            return -1;        } else {            for (int i = value.length - 1; i >= 0; i--) {                if (obj == value[i]) {                    return i;                }            }            return -1;// return 作用:1,返回出去值,2,结束语句。        }    }    public void rangleCheck(int index) {        if (index < 0 || index > size - 1) {// [0,size-1]            try {                throw new Exception();            } catch (Exception e) {                e.printStackTrace();            }        }    }    public Object set(int index, Object object) {        rangleCheck(index);        Object old = value[index];        value[index] = object;        return old;    }    public Object get(int index) {        rangleCheck(index);        return value[index];    }    public static void main(String[] args) {        MyArrayList list = new MyArrayList();        list.add("aaa");        list.add(new Human("高淇"));        list.add("bbb");        list.add("bbb");        list.add("bbb");        list.add("bbb");        Human h = (Human) list.get(1);        System.out.println(h.getName());        System.out.println("*********************");        System.out.println(list.get(0));        System.out.println(list.get(1));        System.out.println(list.get(2));        System.out.println("*******************");        System.out.println(list.size);    }}class Human {    private String name;    public Human(String name) {        this.name = name;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }}
阅读全文
0 0
原创粉丝点击