自定义实现ArrayList中的常用方法

package mycollection;

/**

  • 1自定义实现一个ArrayList
  • 2增加泛型
  • 3增加数组扩容
  • 4增加set和get方法
  • 增加:数组边界的检查
  • 5增加remove方法
  • @author

*/
public class TestArrayList {

private	Object[] elementDate;
private int size;
private static final int DEFALT_CAPACITY = 10;

public TestArrayList5() {
	elementDate = new Object[DEFALT_CAPACITY];
}

public TestArrayList5(int a){
	
	if(a<0){
		throw new RuntimeException("容器容量不能为负数");
	}else if(a == 0){
		elementDate = new Object[DEFALT_CAPACITY];
	}else{
		elementDate = new Object[a];
	}
}

public int size(){
	return size;
}

public boolean isEmpty(){
	return size==0?true:false;
}

public void add(E e){
	
	//什么时候扩容
	if(size == elementDate.length ){

		//扩容
		Object[] newArray = new Object[elementDate.length+(elementDate.length>>1)];//elementDate.length>>1 要括起来 加法的优先级高
		System.arraycopy(elementDate, 0, newArray, 0, elementDate.length);
		elementDate = newArray;
	}
	elementDate[size++] = e;
}

public E get(int index){
	return (E)elementDate[index];
}

public void set(E e,int index){
	
	checkRange(index);
	
	elementDate[index] = e;
}

public void checkRange(int index){//检查范围
		//索引判断[0,size)
	if(index<0 || index>size){
		//不合法
		throw new RuntimeException("索引不合法!");
	}
}

public void remove(E e){
	//e将它和所有元素进行比较 获得第一个为true的 返回
	for(int i=0; i<size; i++){
		if(e.equals(get(i))){	//容器中所有的比较操作都使用equals
	
			//将该元素从此处移除
			
			remove(i);
			
		}
	}
}

public void remove(int index){
	int mumMoved = elementDate.length-index-1;
	if(mumMoved>0){
	System.arraycopy(elementDate, index+1, elementDate, index, mumMoved);
	}
	elementDate[--size] = null;
	
}

@Override
public String toString() {
	StringBuilder sb = new StringBuilder();
	
	//[a,b,c]
	sb.append("[");
	for(int i=0; i<size; i++){
		sb.append(elementDate[i]+",");
	}
	sb.setCharAt(sb.length()-1, ']');
	
	return sb.toString();
	
}


public static void main(String[] args) {
	TestArrayList5<String> a1 = new TestArrayList5<>();
	
	
	for(int i=0; i<10; i++){
		a1.add("a"+i);
	}
	
	a1.set("aaaa", 3);
	
	System.out.println(a1);
	
	System.out.println(a1.get(3));
	
	a1.remove("aaaa");
	a1.remove(1);
	System.out.println(a1);
	
	System.out.println(a1.size);
	System.out.println(a1.isEmpty());
}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值