今日份代码:模拟封装

本文通过实例探讨了Java编程中的模拟封装概念,详细解释了如何利用类和对象来实现数据隐藏与访问控制,以提高代码的健壮性和可维护性。通过对私有属性、构造器、getter/setter方法的运用,展示了封装在实际开发中的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package test;

public class ArrayBox<E> {
	
	private static final int DEFAULT_CAPACITY = 1;
	public Object[] array;
	private int size = 0;

	public ArrayBox() {
		array = new Object[DEFAULT_CAPACITY];
	}

	public ArrayBox(int initialCapacity) {
		array = new Object[initialCapacity];
	}

//minCapacity最小容量
	private void ensureCapacity(int minCapacity) {

		if (minCapacity - array.length > 0) {

			this.grow(minCapacity);
		}
	}
	

	private void grow(int minCapacity) {

		int oldLength = array.length;
	
		int newCapacity = oldLength + (oldLength>>1);
		
		//节约
		if (newCapacity - minCapacity < 0) {
			newCapacity = minCapacity;

		}
		

		array=this.newArrObjects(newCapacity, array);
	}

	//将旧数组的元素放到新数组
	private Object[] newArrObjects(int arrayLength, Object[] array) {

		Object[] newArray = new Object[arrayLength];
		Object object=new Object();
		for (int i = 0; i < array.length; i++) {
		
			object = array[i];
	
			for (int j = i; j < newArray.length; j++) {
				//解释一下
				 /*如果是j=0
	            		前面的for循环每次循环中得出的e
	   	        		后面for循环每次都是从0开始的
	            		假设第一次e=1;
	            		newArray[1,1,1,1,1,1];
	            		假设第二次e=2;
	            		newArray[2,2,2,2,2,2];
	            
	            	j=i
	            		假设第一次e=1;
	            		newArray[1,1,1,1,1,1];
	            		i++;
	            
	            		假设第一次e=2;
	            		newArray[1,2,2,2,2,2];
	            		i++;
	            		依次。。。。。
	            */
				newArray[j] = object;

			}
		}

		return newArray;
	}

	// 添加方法
	public void add(Object object) {

		this.ensureCapacity(size + 1);
		array[size++] = object;
	}

	// 移除方法
	public void remove(int index) {
		for (int i = index; i < size - 1; i++) {
			array[i] = array[i + 1];
		}
		array[--size] = null;
	}

	// 修改方法
	public void update(int index, Object object) {
		array[index] = object;
	}

	// 获取方法
	public Object get(int index) {
		Object object = array[index];
		return object;
	}

	public static void main(String[] args) {
		ArrayBox<Integer> box = new ArrayBox<Integer>();
		box.add(1);
		box.add(2);
		box.add(3);
		box.update(2, 1);
		box.remove(1);
	for (int i = 0; i < box.size; i++) {
		System.out.println(box.get(i));
	}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值