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];
}
}

 

你可能感兴趣的:(java)