自己实现的数组列表

package yzy.datastructure.myArrayList;

import java.util.Arrays;

public class MyArrayList<T>
{
 @SuppressWarnings("unchecked")
 public MyArrayList()
 {
  elements = (T[]) new Object[initCapicity];
 }
 
 public int size()
 {
  return length;
 }
 
 public void add(T a)
 {
  if(length == maxLength)
  {
   resize();
  }
  elements[length++] = a;
 }
 
 public void add(int index,T a)
 { /*插入位置不合理*/
  if(index < 1 || index >length + 1)
   return;
  if(length == maxLength)
  {
   resize();
  }
  for(int i = length - 1;i >= index - 1;i--)
  {
   elements[i+1] = elements[i];
  }
  elements[index-1] = a;
  length++;
 }
 
 private void resize()
 { /*重新分配数组大小*/
  elements = Arrays.copyOf(elements, length + increment);
  maxLength += increment;
  System.out.println(length);
 }
 
 public T get(int index)
 {
  return elements[index];
 }
 
 public int indexOf(T a)
 {
  for(int i = 0;i < length;i++)
  {
   if(elements[i].equals(a))
   {
    return i;
   }
  }
  return -1;
 }
 
 public boolean isEmpty()
 {
  return length == 0?true:false;
 }
 
 public T remove(int index)
 {
  T tmp = elements[index - 1];
  for(int i = index-1;i < length - 1;i++)
  {
   elements[i] = elements[i+1];
  }
  length--;
  return tmp;
 }
 
 public boolean remove(T a)
 {
  for(int i = 0;i < length;i++)
  {
   if(elements[i].equals(a))
   {
    remove(i+1);
    return true;
   }
  }
  return false;
 }
 
 public T set(int index,T a)
 {
  T tmp = elements[index-1];
  elements[index-1] = a;
  return tmp;
 }
 
 public void show()
 {
  System.out.println("length is: " + size() + ",maxLength is: " + maxLength);
  for(int i = 0;i < length;i++)
   System.out.print(elements[i]);
  System.out.println("");
 }
 
 private T[] elements;
 private int length = 0;
 private static final int initCapicity = 3;
 private static final int increment = 3;
 private int maxLength = initCapicity;
}

posted @ 2011-08-09 11:33  图形学小菜鸟  阅读(160)  评论(0编辑  收藏  举报