写一个简易的arraylist

arraylist是java中一个集合,它和linkedlist都为list子类

为了学习list于是自己写了一个简单的arraylist

因为arraylist的底层数组,所以和顺序表有几乎相同

 


package Array;


public class MyArrayList<T>  {
private static final int DEFAULT_CAPACITY=10;
private int thesize;
private T[] theItems;

//构造方法
@SuppressWarnings("unchecked")
public MyArrayList(){
this.theItems=(T[]) new Object[DEFAULT_CAPACITY];
}
//定义初始长度的构造方法
@SuppressWarnings("unchecked")
public MyArrayList(int initialCapacity){
	if(initialCapacity>0) {
	this.theItems=(T[]) new Object[initialCapacity];
	}else if(initialCapacity==0) {
		this.thesize=0;
		this.theItems=(T[]) new Object[DEFAULT_CAPACITY];
	}else {
		throw new IllegalArgumentException("输入有误 "+initialCapacity);
	}
	
}
//添加指定元素指定元素
public boolean add(T newelement) {
	if(thesize>theItems.length) {
		grow();
	}
	theItems[thesize++]=newelement;
	return true;
}
//扩容为原来得1.5
private void grow() {
	int newTheSize=thesize+(thesize>>1);	
	T [] newTheTtems=(T[]) new Object[newTheSize];
	for(int i=0;i<thesize;i++) {
		newTheTtems[i]=theItems[i];
	}
	theItems=newTheTtems;
}
//获取指定位置数据
public T get(int index) {
	if(index<0||index>=size()) {
		throw new IllegalArgumentException("输入有误 "+index);
	}
	return this.theItems[index];
}
//将指定位置设置指定元素
public boolean set(int index ,T newT) {
	if(index<0||index>=size()) {
		throw new IllegalArgumentException("输入有误 "+index);
	}
	this.theItems[index]=newT;
	return true;
}
//移除指定位置元素
public boolean remove(int index) {
	if(index<0||index>=size()) {
		throw new IllegalArgumentException("输入有误 "+index);
	}
	for(int i=index;i<thesize;i++) {
		theItems[i-1]=theItems[i];
	}
	thesize--;
	return true;
}
//移除所有元素
private void removeall() {
	thesize=0;
}
//长度
public int size() {
	return thesize;
}
//是否为空
public Boolean isEmpty() {
	return size()==0;
}

}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值