/**
* @version 1.0.0
* @auther 张世翔
* @date 2022/4/6 13:41
*/
public class ArrayList implements List{
/**
* 底层存储
*/
private Object[] elementData;
/**
* 元素的数量
*/
private int size;
public ArrayList() {
this(10);
}
public ArrayList(int initialCapacity) throws IllegalArgumentException {
if (initialCapacity < 0) {
throw new IllegalArgumentException("Illegal Capacity: " + initialCapacity);
}
// 初始化数组
this.elementData = new Object[initialCapacity];
}
public int size() {
return this.size;
}
/**
* 末尾添加指定对象
* @param object 指定对象
* @return
*/
public boolean add(Object object) {
// 确保存储空间能够存储新的数据
ensureCapacity(size + 1);
int count = size;
elementData[size++] = object;
if (count < size) {
return true;
}
return false;
}
/**
* 在指定index新增
* @param index 下标
* @param object 添加的元素
*/
@Override
public void add(int index, Object object) {
ensureCapacity(size+1);
System.arraycopy(elementData,index,elementData,index+1,size-index);
size++;
elementData[index]=object;
}
@Override
public void addAll(List arrayList) {
size=size+arrayList.size();
System.arraycopy(elementData,size-1,arrayList,0,arrayList.size());
}
/**
* 确保存储空间能够存储新的数据
* @param minCapacity
*/
private void ensureCapacity(int minCapacity) {
if (minCapacity == elementData.length){
int oldCapacity = elementData.length;
// 新数组长度为原数组长度的1.5倍
// oldCapacity >> 1 理解成 oldCapacity/2 新数组的长度是原来长度1.5倍
int newCapacity = oldCapacity + (oldCapacity >> 1);
// 使用传入的值和原数组1.5的最大值作为新数组的长度
newCapacity = Math.max(minCapacity,newCapacity);
// 空间不够数组扩容
elementData = Arrays.copyOf(elementData,newCapacity);
}
}
/**
* 输出指定下标元素
* @param index
* @return
*/
public Object get(int index) {
return elementData[index];
}
/**
* 修改指定下标
* @param index
* @param object
*/
public void set(int index,Object object){
elementData[index] = object;
}
/**
* 清空
*/
@Override
public void clear() {
int count =size;
for (int i =0;i<count;i++){
remove(0);
}
//遍历置空,不适合多线程
//for
//容量归零size = 0;
}
@Override
public Object[] toArray() {
Object[] objects = new Object[size];
for (int i =0;i<size;i++){
objects[i]=elementData[i];
}
return objects;
}
/**
* 移除指定下标
* @param index
*/
public void remove(int index){
System.arraycopy(elementData ,index + 1,elementData ,index ,size - index - 1);
elementData[--size] = null;
}
@Override
public String toString() {
String msg = "[";
for (int i = 0; i < size; i++) {
msg += elementData[i];
if (i < size - 1) {
msg += ", ";
}
}
msg += "]";
return msg;
}
/**
* 输出指定下标元素
* @param object
* @return
*/
public int indexOf(Object object){
for (int i = 0; i < size; i++) {
if(elementData[i] == object) {
return i;
}
}
return -1;
}
/**
* 移除指定元素
* @param object
* @return
*/
public boolean remove(Object object){
if (contains(object)){
remove(indexOf(object));
return true;
}
return false;
}
public boolean contains(Object object){
for (int i = 0; i < size; i++) {
if(elementData[i] == object) {
return true;
}
}
return false;
}
}
二十、手写ArrayList方法
最新推荐文章于 2022-04-15 11:45:28 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)