CSDN博客

img mysine

关于Vector的优化,自制StringVector

发表于2002/11/1 23:33:00  828人阅读

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

0 0

相关博文

我的热门文章

img
取 消
img