ITeye博客

ArrayList 列表

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

列表的简单实现,只能存储非负整数

List 也属于ADT(抽象数据类型),此处是使用Array类实现List。

另外一个实现请参见LinkedList

 

 

设置,取值的方法:

set,get

添加,插入,删除的方法

add ,insert, remove

其他方法

getLength, indexOf

 

class ArrayList {
	private Array array = new Array();
	void add(int value) {
		array.set(value,array.getLength());
	}

	void set(int value, int pos) {
		assert pos < array.getLength();
		array.set(value,pos);
	}

	int get(int pos) {
		assert pos < array.getLength();
		return array.get(pos);
	}

	void insert(int value,int pos) {
		assert pos <= array.getLength();
		for(int i=array.getLength(); i>pos ; i--) {
			array.set(array.get(i-1),i);
		}
		array.set(value,pos);
	}

	int remove(int pos) {
		int result = array.get(pos);
		for(int i=pos+1; i<array.getLength(); i++){
			array.set(array.get(i),i-1);	
		}
		array.truncate(array.getLength() - 1);
		return result;
	}

	int getLength() {
		return array.getLength();
	}

	int indexOf(int value) {
		for(int i=0; i<array.getLength(); i++) {
			if (array.get(i) == value) return i;
		}
		return -1;
	}
}

评论(0)

暂无评论。

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