java_ArrayList的简单实现

/*1、使用数组模拟实现java中的ArrayList,模仿StringBuilder
 *2、对java中的ArrayList的底层实现进行分析
*/

public class MyArrayList {
	
	//The value is used for Object storage.
	private Object[] value;
	
	//The size is the number of Objects used.
	private int size;
	
	
	//Two Constructors.default:size=16; DIY:input size.
	public MyArrayList() {
		this(16);
	}
	
	public MyArrayList(int size) {
		if(size<0){
			try {
				throw new Exception();
			} 
			catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		value = new Object[size];
		
	}
	
	
	//method_one: add, the method of adding an object to the "MyArrayList". 
	public void add(Object obj){
		value[size] = obj;
		size++;
		//if old one is too small.
		if(size>=value.length){
			int newCapacity = value.length*2;
			Object[] newList = new Object[newCapacity];
			
			//copy from old small "MyArrayList".
//			System.arraycopy(src, srcPos, dest, destPos, length);
			for(int i=0;i<value.length;i++){
				newList[i] = value[i];
			}
			
			value = newList;
		}
	}
	
	//method_two: get, the method of getting an object from the "MyArrayList".
	//You must input an element's index you want. 
	public Object get(int index){
		
		//if IndexOutOfBoundsException occurred.
		if(index<0||index>size-1){
			try {
				throw new Exception();
			} 
			catch (Exception e) {
				e.printStackTrace();
			}
			
		}
		
		return value[index];
	}
	
	
	//method_three: size, the method of getting length of "MyArrayList".
	public int size(){
		return size;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值