纯手写ArrayList集合实现

纯手写ArrayList集合实现

实现类:

package socketDemo;

import java.util.Arrays;

/**
 * ArrayList集合实现
 * @author yb
 *
 */
public class ArrayList {
    //定义Object类型的数组
	Object[] data ;
    //统计变量,用于统计数组元素的真实个数
	int size;
	public ArrayList() {
        //初始化长度为10
		this(10);
	}
	ArrayList(int length){
        //通过构造方法指定数组的长度
		data = new Object[length];
	}
    	//长度
	public int getLength(){
		return size;
	}
    //为了方便看效果,我们覆写toString()方法
    //为了打印真实的数组内容,除去空余的默认值
    @Override
	public String toString() {
        //构建一个新的数组,长度为size
		Object[] newdata = new Object[size];
        //将data中的元素拷贝到新数组中
		System.arraycopy(data, 0, newdata, 0, size);
        //利用Arrays类,将数组转换成字符串
		return Arrays.toString(newdata);
	}
	//增
	void add(Object obj){
        //如果数组满了
		if(size>=data.length){
            //构建一个新的数组,容量默认增加*1.5+1
//			int newLength = (int) (data.length*1.5+1);
//			Object[] newdata = new Object[newLength];
			Object[] newdata = new Object[size+1];
            //将原来的数组内容拷贝到扩容后的数组中 Object src : 原数组
//			   int srcPos : 从元数据的起始位置开始
//			   Object dest : 目标数组
//			   int destPos : 目标数组的开始起始位置
//			   int length  : 要copy的数组的长度
			System.arraycopy(data, 0, newdata, 0, size);
			data = newdata;
		}
        //将新增的元素添加在数组的末尾
		data[size] = obj;
        //数组真实长度自增1
		size++;
	}

	//查找指定索引处的元素;
	public Object getElementByIndex(int index){
		if(index<0||index>size){
			throw new ArrayIndexOutOfBoundsException("数组越界了,索引范围是:0~"+(size-1));
		}
		return data[index];
	}
	//查找指定元素第一次出现的索引
	public int getFirstIndexByElement(Object obj){
		for (int i = 0; i < size; i++) {
			if(obj.equals(data[i])){
				return i;
			}
		}
		return -1;//没有找到
	}
    //删除指定索引处的元素
	public void deleteElementByIndex(int index){
		if(index<0||index>size){
			throw new ArrayIndexOutOfBoundsException("数组越界了,索引范围是:0~"+(size-1));
		}
//		System.arraycopy(data, index+1, data, index, size-index-1);
		Object[] newdata = new Object[--size];
		for(int i=0;i<data.length;i++){
			if(i!=index){
				if(i>index){
					newdata[i-1] = data[i];
				}else{
					newdata[i] = data[i];
				}
			}
		}
		data = newdata;
//		size--;
	}
	//删除指定的第一个元素
	public void deleteFirstElement(Object obj){
		int index = getFirstIndexByElement(obj);
//		System.out.println(index);
		deleteElementByIndex(index);
	}	

}

测试类:

package socketDemo;

public class TestList {

	public static void main(String[] args) {
		ArrayList list = new ArrayList();
        for(int i=0;i<12;i++){
    	 list.add(i);
        }
        list.deleteElementByIndex(3);
        for(int j=0;j<list.data.length;j++){
        	System.out.println(list.getElementByIndex(j));
        }
	}

}

猜你喜欢

转载自blog.csdn.net/m0_46266503/article/details/106426274