`
vtrtbb
  • 浏览: 353242 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

list基本实现

    博客分类:
  • java
阅读更多
复习数据结构,一个基本list
import java.util.Iterator;
import java.util.NoSuchElementException;

public class MyArrayList implements Iterable {

	private static final int DEFAULT_CAPACITY = 10;

	private int theSize;

	private Object[] theItems;

	public MyArrayList(){
		clear();
	}
	
	public void clear() {
		theSize = 0;
		ensureCapacity(DEFAULT_CAPACITY);
	}
	
	public int size() {
		return theSize;
	}

	public boolean isEmpty() {
		return size() == 0;
	}

	public void trimToSize() {
		ensureCapacity(size());
	}

	public Object get(int idx) {
		if (idx < 0 || idx >= size()) {
			throw new ArrayIndexOutOfBoundsException();
		}
		return theItems[idx];
	}

	public Object set(int idx, Object newVal) {
		if (idx < 0 || idx >= size()) {
			throw new ArrayIndexOutOfBoundsException();
		}
		Object old = theItems[idx];
		theItems[idx] = newVal;
		return old;
	}

	public void ensureCapacity(int newCapacity) {
		if (newCapacity < theSize) {
			return;
		}
		Object[] old = theItems;
		theItems = (Object[]) new Object[newCapacity];
		for (int i = 0; i < size(); i++) {
			theItems[i] = old[i];
		}
	}
	
	public boolean add(Object x) {
		add(size(),x);
		return true;
	}
	
	public void add(int idx,Object x) {
		System.out.println("---"+theItems.length+"---"+size()+"--"+theSize+"--"+idx);
		if (theItems.length == size()) {
			ensureCapacity(size() * 2 + 1);
		}
		for(int i = theSize; i > idx;i--) {
			theItems[i] = theItems[i-1];
			System.out.println("===="+theItems[i-1]);
		}
		theItems[idx] = x;
		theSize++;
	}
	
	public Object remove(int idx) {
		Object removedItem = theItems[idx];
		for (int i = idx; i < size() - 1 ;i++) 
			theItems[i] = theItems[i+1];
		theSize--;
		return removedItem;
	}
	

	@Override
	public Iterator iterator() {
		return new ArrayLIstIterator();
	}
	
	private class ArrayLIstIterator implements Iterator<Object>{
		private int current = 0;
		
		public boolean hasNext(){
			return current < size();
		}
		
		public Object next() {
			if(!hasNext()) {
				throw new NoSuchElementException();
			}
			return theItems[current++];
		}
		public void remove() {
			MyArrayList.this.remove(--current);
		}
	}
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics