前言:最近参加一次面试,感觉好多基础东西都已经忘记。也许是因为这两年多的时间把大多的时间放在相关业务开发,所以对一些知识只会用,不太会说。另外还有个问题就是现在编辑器太发达了,打一个字母提示就带出来。所以有些关键字只认识,拼写却忘记了。所以从现在起利用休息时间从数据结构重新学习。好了,不废话了,开始上代码(代码按书中代码打出来的)
import java.util.Iterator;
import java.util.NoSuchElementException;
public class MyArrayList<E> {
/**
* 初始化大小
*/
private static final int DEFAULT_CAPACITY = 10;
/**
* 集合大小
*/
private int theSize;
/**
* 集合元素
*/
private E[] theItems;
/**
* 构造方法
*/
public MyArrayList(){
doClear();
}
public void clear(){
doClear();
}
private void doClear(){
theSize = 0 ;
ensureCapacity(DEFAULT_CAPACITY);
}
public int size(){
return theSize;
}
/**
* 判断集合是否为空
* @return
*/
public boolean isEmpty(){
return size()==0;
}
public void trimToSize(){
ensureCapacity(size());
}
/**
* 获取索引为idx的元素
* @param idx
* @return
*/
public E get(int idx){
if(idx<0||idx>=size())
throw new ArrayIndexOutOfBoundsException();
return theItems[idx];
}
/**
* 为索引idx 赋值
* @param idx
* @param newVal
* @return
*/
public E set(int idx,E newVal){
if(idx<0||idx>=size())
throw new ArrayIndexOutOfBoundsException();
E old = theItems[idx];
theItems[idx] = newVal;
return old;
}
/**
* 开辟newCapactity数据空间
* @param newCapactity
*/
public void ensureCapacity(int newCapactity){
if(newCapactity<theSize)
return;
E[] old = theItems;
theItems = (E[]) new Object[newCapactity];
for(int i = 0;i<size();i++){
theItems[i] = old[i];
}
}
/**
* 添加元素
* @param x
* @return
*/
public boolean add(E x){
add(size(),x);
return true;
}
/**
* 在索引idx插入新的元素
* @param idx
* @param x
*/
public void add(int idx,E x){
if(theItems.length==size())
ensureCapacity(size()*2+1);
for(int i = theSize;i>idx;i--)//将idx之后的元素向后移动
theItems[i] = theItems[i-1];
theItems[idx] = x;
theSize++;
}
/**
* 移除索引idx的元素
* @param idx
* @return
*/
public E remove(int idx){
E removeItem = theItems[idx];
for(int i = idx ;i<size()-1;i++)//将idx 之后的元素向前移动
theItems[i] = theItems[i+1];
theSize--;
return removeItem;
}
public Iterator<E> iterator(){//迭代器
return new ArrayListIterator();
}
private class ArrayListIterator implements Iterator<E>{
private int current;//当前迭代器指向位置
public boolean hasNext() {//是否含有下个元素
return current<size();
}
public E next() {
return theItems[current++];
}
public void remove(){
MyArrayList.this.remove(--current);
}
}
}
最后,请问各种同行者,是否说下学习建议或者推荐学习的书籍