对数组中进行插入,查找,删除元素

利用数据结构对数组进行插入元素,查找,删除
一,对数组的两种定义
1.不明确数组内部

int[]arr = new int[10];
		for(int i=0;i<arr.length;i++) {
			arr[i] = i;

2.明确数组内存

int[] scores = new int[] {100,97,74};	
		for(int j=0;j<scores.length;j++) {
			System.out.println(scores[j]);

二,构造函数传入数组容量

public Array(int capacity) {
		data = new int[capacity];
size = 0;
	}
public Array() {
	this(capacity:10);

三,向其中添加元素

public void add(int index,int e) {
		
		if(size == data.length)//考虑其中长度的问题
			throw new IllegalArgumentException("Add failed.Array is full.");
			
		if(index < 0 || index > size)//当索引为0或者超出数组长度进行异常的捕获
			throw new IllegalArgumentException("Add failed.Require index >= 0 and index <= size.");
		for(int i=size - 1;i >= index;i--)
			data[i+1] = data[i];
		
		data[index] = e;
		size ++;
	}

四,删除元素

public int remove(int index) {
		if(index < 0|| index >= size)
			throw new IllegalArgumentException("Remove failed.Index is illegal.");
		
		int ret = data[index];
		for(int i = index+1;i < size; i++)
			data[i-1] = data[i];
		size --;
		return ret;
		
	}

删除元素,以及增加元素,其本质是先对原本数组中的内容进行复制,再进行删除或者增加
同时注意数组长度容量问题进行及时调整

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值