模拟实现ArrayList容器的底层实现


public class Human {
    private String name;

public Human(String name) {
	super();
	this.name = name;
}

public String getName() {
	return name;
}

public void setName(String name) {
	this.name = name;
}

}

 

import java.util.ArrayList;

/**
 * 模拟实现JDK中提供的ArrayList类
 * 
 * @author 86176
 *
 */
public class MyArrayList {
	/**
	 * The value is used for character storage.
	 */
	private Object[] value;

	/**
	 * The size is the number of characters used.
	 */
	private int size;

//创建一个容器
	public MyArrayList() {
		// value =new Object[16];
		this(10);
	}

	public MyArrayList(int size) {
		if (size < 0) {
			try {
				throw new Exception(); // 手动抛出一个异常
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		value = new Object[size];
	}

	// 容器中方法
	public int size() {
		return size();
	}

	public boolean isEmpty() {
		return size == 0;
	}

	public int indexOf(Object obj) {
		if (obj == null) {
			return -1;
		} else {
			for (int i = 0; i < value.length; i++) {
				if (obj == value[i]) {
					return i;
				}
			}
			return -1;
		}
	}
	public int lastindexOf(Object obj) {
		if (obj == null) {
			return -1;
		} else {
			for (int i = value.length-1; i >=0; i--) {
				if (obj == value[i]) {
					return i;
				}
			}
			return -1;
		}
	}
	public Object set(int index,  Object object) {
		
		rangeCheck(index);
         Object old=value[index];
        value[index] = object;
        return old;
    }
public void rangeCheck(int index) {
	if (index < 0 || index > size - 1) { // [0,size-1]
		try {
			throw new Exception(); // 手动抛出一个异常
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
	public void add(Object obj) {
		value[size] = obj;
		size++;

		if (size >= value.length) {
			// 装不下,扩容吧
			int newCapacity = value.length * 2;
			Object[] newList = new Object[newCapacity];
			// System.arraycopy(src, srcPos, dest, destPos, length);
			for (int i = 0; i < value.length; i++) {
				newList[i] = value[i];
			}
			value = newList;
		}
	}

	public Object get(int index) {
		rangeCheck(index);
		return value[index];
	}

	public static void main(String[] args) {
		MyArrayList list = new MyArrayList(2);
		list.add("aaa");
		list.add(new Human("张三"));
		list.add("bbb");
		list.add("bbb");
		list.add("bbb");
		list.add("bbb");
		ArrayList list2;

		Human h = (Human) list.get(1);// 强制转换
		System.out.println(h.getName());
		System.out.println(list.get(2));
		System.out.println(list.get(0));
		// System.out.println(list.get(3));//超出范围,抛出异常
		System.out.println(list.size);

	}
}

输出:
张三
bbb
aaa
6

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值