数据结构------数组中查询元素和修改元素

	// 获取index索引位置的元素
	public int 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, int e) {
		if (index < 0 || index >= size) {
			throw new IllegalArgumentException("Set failed. Index is illegal.");
		}
		data[index] = e;
	}

	// 查找数组中是否有元素e
	public boolean contains(int e) {
		for (int i = 0; i < size; i++) {
			if (data[i] == e) {
				return true;
			}

		}
		return false;
	}

	// 查找数组中元素e所在的索引,如果不存在元素 e,则返回-1
	public int find(int e) {
		for (int i = 0; i < size; i++) {
			if (data[i] == e) {
				return i;
			}

		}
		return -1;
	}

	@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();
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值