zoukankan      html  css  js  c++  java
  • 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];
    }
    }
  • 相关阅读:
    java23中设计模式之策略模式
    java23中设计模式之模板模式
    java23中设计模式之备忘录模式
    java23中设计模式之命令模式
    java23中设计模式之中介者模式
    java23中设计模式之迭代器模式
    java23中设计模式只责任链模式
    web service -- jdk spring cxf ajax 开发(2)
    洛谷 P1566 加等式
    洛谷 P1439 【模板】最长公共子序列
  • 原文地址:https://www.cnblogs.com/xinyuyuanm/p/2993357.html
Copyright © 2011-2022 走看看