總是學不精,學不透

第一篇:看一個老師寫的,還是差一段距離~

public class Arraytwo <E> {
	private E[] data;
	private int size;
	
	// 構造函數,傳入數組的容量capacity構造dynamic
	@SuppressWarnings("unchecked")
	public Arraytwo(int capacity) {
		data = (E[])new Object[capacity]; // 一種父調子的方法,1.5版本後才加入的容器類用法
		size = 0;
	}
	
	// 無參數構造函數,capacity默認容量爲10
	public Arraytwo() { this(10);}
	
	// 獲取數組中的元素個數
	public int getsize() { return size; }
	
	// 獲取數組的容量
	public int getcapacity() { return data.length; }
	
	// 返回數組是否爲空
	public boolean isEmpty() { return size == 0; }
	
	// 向所有元素後添加一個新元素e
	public void addLast(E e) { add(size, e); }
	
	// 在所有元素前添加一個新元素
	public void addFirst(E e) { add(0, e); }
	
	// 從第index個位置插入一個新元素e
	public void add(int index, E e) {
		
		if(index < 0 || index > size)
			throw new IllegalArgumentException("Add failed. Require index >= 0 add size");
		
		if(size == data.length)
			resize(2 * data.length); // 動態數組用異常更改爲數組長度乘2稱爲動態數組
		
		for (int i = size - 1 ; i >= index ; i --)
			data[i + 1] = data[i];
			
		data[index] = e;
		size ++;
	}

	// 獲取index索引位置的元素
	public E get(int index) {
		if(index < 0 || index >= size)
			throw new IllegalArgumentException("Get failed.Index is illegal.");
		return data[index];
	}
	
	// 修改index索引位置元素爲e
	public void set(int index, E e) {
		if(index < 0 || index >= size)
			throw new IllegalArgumentException("Get failed.Index is illegal.");
		data[index] = e;
	}
	
	// 查找數組中是否有元素e
	public boolean contains(E e) {
		for (int i = 0; i < size; i ++) {
			if (data[i].equals(e))
				return true;
		}
		return false;
	}
	
	// 查找數組中元素e所在的索引,如果不存在元素e,則返回-1
	public int find(E e) {
		for (int i = 0; i < size; i ++) {
			if(data[i].equals(e))
				return i;
		}
		return -1;
	}
	
	// 從數組中刪除index位置的元素,返回刪除的元素
	public E remove (int index) {
		if(index < 0 || index >= size)
			throw new IllegalAccessError("Remove failed. Index is illegal.");
		E ret = data[index];
		for (int i = index + 1; i < size; i ++)
			data[i - 1] = data[i];
		size --;
		data[size] = null; // loitering objects != memory leak
		
		if(size == data.length/2)
			resize (data.length/2) ;
		
		return ret;
	}
	
	// 從數組中刪除第一個元素,返回刪除的元素
	public E removeFirst() {
		return remove(0);
	}
	
	// 從數組中刪除最後一個元素,返回刪除的元素
	public E removeLast() {
		return remove(size - 1);
	}
	
	// 從數組中刪除元素e
	public void removeElement(E e) {
		int index = find(e);
		if(index != -1)
			remove(index);
	}
	
	@Override
	public String toString() {
		StringBuilder res = new StringBuilder();
		res.append(String.format("Array: size = %d , capacity = %d\n",size, data.length));
		res.append('[');
		for (int i = 0 ; i < size ; i ++) {
			res.append(data[i]);
			if(i != size - 1)
				res.append(",");
		}
		res.append(']');
		return res.toString();
	}
	
	private void resize(int newCapacity) {
		@SuppressWarnings("unchecked")
		E[] newData = (E[])new Object[newCapacity];
		for (int i = 0; i < size; i++)
			newData[i] = data[i]; 
		data = newData;
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章