顺序链表-MyArrayList的实现

来源:互联网 发布:广州腾科java培训 编辑:程序博客网 时间:2024/06/05 17:19
package lpc.Algorithm;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class MyArrayList<T> implements Iterable<T>{
 
 //设置数组初始大小
 public static final int DEFAULT_CAPACITY = 10;
 
 //记录数据已的存储数量
 private int theSize;
 //数组
 private T[] theItems;
 
 //构造函数,初始数组,数组长度为  DEFAULT_CAPACITY
 public MyArrayList() {
  // TODO Auto-generated constructor stub
  //创建泛型数组的方法来创建初始数组
  theItems=(T[])new Object[DEFAULT_CAPACITY];
  //现有0条数据
  theSize=0;
 }
 
 //获取已存储的数据量
 public int size(){
  return theSize;
 }
 //判断是否存在数据
 public boolean isEmpty(){
  return size()==0;
 }
 
 //改变数组长度,(可做扩容时使用)
 public void ensureCapacity(int newCapacity){
  //判断要创建的容量是否能存储的下数据,存不下就返回
  if (newCapacity < size()) {
   return;
  }
  //把眼熟组存入临时变量
  T[] old=theItems;
  
  //创建一个指定容量的新数组(泛型数组)
  theItems = (T[])new Object[newCapacity];
  
  //把原有数据转存到新数组
  for (int i = 0; i < size(); i++) {
   theItems[i] = old[i];
  }
 }
 
 
 
 //把数组长度变为数据个数避免浪费空间
 public void trimToSize(){
  ensureCapacity(size());
 }
 
 //根据索引数,得到数据
 public T get(int index){
  
  //判断是否超出边界
  if(index < 0 || index >= size()){
   throw new ArrayIndexOutOfBoundsException();
  }
  return theItems[index];
 }
 
 //修改制定索引上的数据,并返回被替换的数据
 public T set(int index, T newVal){
  //判断是否超出边界
  if(index < 0 || index >= size()){
   throw new ArrayIndexOutOfBoundsException();
  }
  
  T old= theItems[index];
  //成功替换
  theItems[index]=newVal;
  return old;
 }

 //在制定索引处增加数据
 public void add(int index,T x){
 
  //判断数组长度和数据个数是否相同,若相同,则数组已装满数据,再增加数组需要扩容
  if (theItems.length==size()) {
   //扩容为数据项数的两倍+1
   ensureCapacity(size()*2+1);
  }
  //把在制定索引处的数据后移一项
  for (int i = size(); i > index; i--) {
   theItems[i] = theItems[i-1];
  }
  //把数据插入倒指定位置
  theItems[index]=x;
  
  //把数据项数增加1
  theSize++;
 }
 
 //在末尾增加数据项
 public boolean add(T x){
  add( size() , x);
  return true;
 }
 
 //删除制定索引处的数据
 public T remove( int index){
  T removedItem = theItems[ index ];
  for (int i = index; i < size()-1; i++) {
   theItems[i] = theItems[i+1];
  }
  theSize --;
  return removedItem;
 };
 
 public Iterator<T> iterator() {
  // TODO Auto-generated method stub
  return new Iterator<T>() {
   
   private int current = 0;
   
   public boolean hasNext() {
    // TODO Auto-generated method stub
    return current < size();
   }

   public T next() {
    // TODO Auto-generated method stub
    if(!hasNext()){
     throw new NoSuchElementException();
    }
    //返回结果后,current再加1
    return theItems[current++];
   }

   public void remove() {
    // TODO Auto-generated method stub
    //System.out.println("迭代期间不提供删除功能");
    MyArrayList.this.remove(--current);
   }
   
  };
 }

}
0 0
原创粉丝点击