自己实现的带泛型ArrayList

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35529801/article/details/79770907
public class MyArrayList<T> {
	private Object[] arrayList;
	private int size;
	private int capacity;
	
	public MyArrayList() {
		this(10);
	}
	
	public MyArrayList(int capacity) {
		if(capacity <= 0) {
			throw new RuntimeException("必须大于0");
		}
		this.capacity = capacity;
		arrayList = new Object[capacity];
	}
	
	public int size() {
		return size;
	}
	
	public int capacity() {
		return capacity;
	}
	//线性表扩充
	public void extendsArrayList() {
		if(size >= capacity) {
			Object[] newArrayList = new Object[size * 2 + 1];
			this.capacity = size * 2 + 1;
			for(int i=0; i<size; i++) {
				newArrayList[i] = arrayList[i];
			}
			arrayList = newArrayList;
		}
	}
	
	//添加
	public boolean add(T obj) {
		extendsArrayList();
		arrayList[size] = obj;
		size++;
		return true;
	}
	
	//指定位置添加
	public boolean add(int index,T obj) {
		extendsArrayList();
		
		if(index < size && index >=0) {
			for(int i=size; i>=index; i--) {
				arrayList[i+1] = arrayList[i];
			}
			arrayList[index] = obj;
			size++;
			return true;
		} else if(index == size){
			add(obj);
			return true;
		} else {
			return false;
		}
	}
	
	//删除
	public boolean remove(int index) {
		if(index < size) {
			for(int i=index; i<size -1; i++) {
				arrayList[i] = arrayList[i+1];
			}
			arrayList[size] = null;
			size--;
			return true;
		} else {
			return false;
		}
	}
	
	//删除
	public boolean remove(T obj) {
		for(int i=0; i<size; i++) {
			if(arrayList[i].equals(obj)) {
				remove(i);
				break;
			}
		}
		
		return false;
	}
	
	//修改
	public boolean set(int index, T obj) {
		if(index < size) {
			arrayList[index] = obj;
			return true;
		} else {
			return false;
		}
	}
	
	//获取
	public T get(int index) {
		if(index <size && index >=0) {
			return (T) arrayList[index];
		} else {
			throw new RuntimeException("数组越界");
		}
	}
	
	//返回指定元素的位置
	public int indexOf(T obj) {
		
		for(int i=0; i<size; i++) {
			if(obj.equals(arrayList[i])) {
				return i;
			}
		}
		
		return -1;
	}
	
	//返回数据对象
	public Object[] toArray() {
		return arrayList;
	}
	
	//查看是否包含
	public boolean contains(T obj) {
		for(int i=0; i<size; i++) {
			if(arrayList[i].equals(obj)) {
				return true;
			}
		}
		return false;
	}
}

猜你喜欢

转载自blog.csdn.net/qq_35529801/article/details/79770907