ITeye博客

Array 可变长一维数组

shenyu · 2008-04-05 16:05 · 数据结构 · Markdown

这是一个可变长数组,对外提供API主要有set,get,可以用它来替代原始数组,不用考虑空间的大小。

此数组是一维的,存放的内容是非负整数,可以考虑用Object,此处用int为的是看起来简单。

每次扩展的长度大体是原来数组长度的10%,也就是oldLenght + oldLength/10,truancate可以缩短数组长度,同时给客户一个减少数组实际占用空间的机会。

class Array {
	private int a[]  = new int[0];
	private int length = 0;
	private static final int WASTER_FACTOR = 10;

	void set(int num, int pos) {
		assert pos >= 0;
		if(pos >= a.length) changeCapacity(pos + getNewCount(a.length));
		if(pos >= length) length = pos + 1;
		a[pos] = num;
	}

	int get(int pos) {
		assert pos >= 0 && pos < length;
		return a[pos];
	}

	int getLength() {
		return length;
	}

	void truncate(int length) {
		assert length >= 0 && length < this.length;
		
		this.length = length;

		if(length > a.length - 2*getNewCount(a.length)) return;
		int[] temp = new int[a.length - getNewCount(a.length)];
		for(int i=0; i<temp.length; i++) {
			temp[i] = a[i];
		}
		a = temp;
	}

	private void changeCapacity(int length) {
		int[] temp = new int[length];
		for(int i=0; i<a.length; i++) {
			temp[i] = a[i];
		}
		a = temp;
	}

	private int getNewCount(int oldLength) {
		return oldLength < 100? WASTER_FACTOR : oldLength/WASTER_FACTOR;
		
	}
}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。