关于Vector的优化,自制StringVector

类别:Java 点击:0 评论:0 推荐:

public class StringVector{

  private static final int DEFAULT_SIZE = 3;
  private String [] data;
  private int count;
  public StringVector() {

    this(DEFAULT_SIZE);
  }
  public StringVector(int initialSize){

    data = new String[initialSize];
  }
  public void add(String str){

    if(str == null)
      return;
    ensureCapacity(count + 1);
    data[count++] = str;
  }
  private void ensureCapacity(int minCapacity){

    int oldCapacity = data.length;
    if (minCapacity > oldCapacity){

      String oldData[] = data;
      int newCapacity = oldCapacity * 2;
      data = new String[newCapacity];
      System.arraycopy(oldData, 0, data, 0, count);
    }
  }
  public void remove(String str){

    if(str == null)
      return;
    for(int i = 0; i < count; i++){

      if(data[i].equals(str)){

        System.arraycopy(data,i+1,data,i,count-1);
        data[--count] = null;
        return;
      }
    }
  }
  public final String get(int index) {

    if(index < 0)
      return null;
    else if(index > count)
      return null;
    else
      return data[index];
  }
  public int size(){

    return count;
  }
}

本文地址:http://com.8s8s.com/it/it18137.htm