• java list内部构造


    看代码吧,如下:
    package com.Core.datastructure;
    import java.lang.reflect.Array;
    import java.util.Collection;
    import junit.framework.TestCase;

    public class ListDemo<T> {
    private int capacity;
    private int size = 0;
    private Object[] elementData;

    public ListDemo(int capcity) {
    this.capacity = capcity;
    elementData = new Object[capacity];
    }

    public ListDemo() {
    this(10);
    }

    public void growCapacity(int growRank) {
    Object newArr = Array.newInstance(elementData.getClass().getComponentType(), capacity
    + growRank);
    System.arraycopy(elementData, 0, newArr, 0,
    Array.getLength(elementData));
    elementData = (Object[]) newArr;
    }

    public void insert(T t) {
    if (capacity > size) {
    elementData[size] = t;
    size++;
    } else {
    growCapacity(1);
    elementData[size] = t;
    size++;
    }
    }

    public void insert(int index, T t) {
    if (index < 0 || index >= size)
    throw new IndexOutOfBoundsException("Index: " + index + ", Size: "
    + size);
    growCapacity(1);
    System.arraycopy(elementData, index, elementData, index + 1, size
    - index);
    elementData[index] = t;
    }

    public boolean remove(T t) {
    if (t == null) {
    for (int i = 0; i < size; i++) {
    if (getEle(i) == null) {
    fastRemove(i);
    return true;
    }
    }
    } else {
    for (int i = 0; i < size; i++) {
    if (getEle(i).equals(t)) {
    fastRemove(i);
    return true;
    }
    }
    }
    return false;

    }

    public T remove(int index) {
                if(index < 0 || index >= size){
                throw new IndexOutOfBoundsException("Index: " + index + ", Size: "
        + size);
                }
                Object obj = elementData[index];
               fastRemove(index);
               return (T) obj;
    }

    public void fastRemove(int index) {
    int numMoved = size - index - 1;
    System.arraycopy(elementData, index + 1, elementData, index, numMoved);
    elementData[--size] = null;
    }

    public T getEle(int index) {
    return (T) elementData[index];
    }
    }
  • 相关阅读:
    一些术语
    Professional Frontend Engineering
    爱上阿森纳,爱上一种信仰
    ThinkPHP 和 UCenter接口的冲突
    这个城市
    来自Google的10条价值观
    如何将Gb2312转为unicode?
    未完成的代码(JS)
    微软也用PHP?!
    博客园对"公告"的Js进行了过滤
  • 原文地址:https://www.cnblogs.com/xinyuyuanm/p/2993357.html
Copyright © 2020-2023  润新知