漫画算法之『数组』-Java演示

欢迎关注我的 微信公众号:破壳Ai,分享最佳学习路径、教程和资源。成长路上,有我陪你。

提示

数组的插入、扩容、删除等操作

/**
 * 数组 - 基本操作
 * @author Guyuehu
 *
 */
public class Main {
	public static void main(String[] args) throws Exception {
		MyArray arrayTest = new MyArray(4);
		arrayTest.insert(0, 6);
		arrayTest.insert(1, 10);
		arrayTest.insert(2, 0);
		arrayTest.insert(3, 7);
		//arrayTest.insert(1, 100);
		arrayTest.insertOutBounds(1, 100);
		arrayTest.delete(2);
		arrayTest.delete(3);
		arrayTest.output();
	}
}

/**
 * 创建数组类
 * @author Guyuehu
 *
 */
class MyArray {
	private int[] array;
	private int size;
	
	public MyArray(int capacity) {
		this.array = new int[capacity];
		this.size = 0;
	}
	
	/**
	 * 从数组中间插入元素
	 * @param  index 	插入元素位置
	 * @param  element 	插入的元素
	 */
	public void insert(int index, int element) throws Exception {
		//超出数组范围抛出异常
		//若index > size 插入的元素就不是顺序放在数组中了
		if(index < 0 || index > size) {
			throw new IndexOutOfBoundsException("超出数组实际元素范围!");
		}
		//从后往前直到inedex位置依次往后移一位
		for(int i = size - 1; i >= index; i--) {
			array[i+1] = array[i];
		}
		//插入
		array[index] = element;
		size++;
	}
	
	/**
	 *超范围插入
	 */
	public void insertOutBounds(int index, int element) throws Exception {
		if(index < 0 || index > size) {
			throw new IndexOutOfBoundsException("超出数组实际元素范围!");
		}
		//数组已满,则对数组扩容
		if(size >= array.length) {
			resize();
		}
		//插入
		for(int i = size - 1; i >= index; i--) {
			array[i+1] = array[i];
		}
		//插入
		array[index] = element;
		size++;
	}
	
	/**
	 * 数组扩容
	 */
	public void resize() {
		int[] arrayNew = new int[2 * array.length];
		System.arraycopy(array, 0, arrayNew, 0, array.length);
		array = arrayNew;
	}
	
	/**
	 * 数组删除元素
	 * @param  index	删除元素位置
	 */
	public int delete(int index) throws Exception {
		if(index < 0 || index > size) {
			throw new IndexOutOfBoundsException("超出数组实际元素范围!");
		}
		int deleteElement = array[index];
		for(int i = index; i < size - 1; i++) {
			array[i] = array[i+1];
		}
		//size-- 很重要,时刻保持与现存数组元素个数等长  
		size--;
		return deleteElement;
	}
	
	/**
	 * 输出数组
	 */
	public void output() {
		for(int i = 0; i < size; i++) {
			System.out.println(array[i]);
		}
	}
	
}

欢迎关注我的 微信公众号:破壳Ai,分享最佳学习路径、教程和资源。成长路上,有我陪你。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值