package com.zhou.collection;
import java.util.Arrays;
public class MyArrayList<T> {
private int Default_initialization_capacity = 10;//默认初始化容量
private Object[] elementData ;//保存元素的数组
private int size = 0;//保存的元素个数
public MyArrayList(int initialCapacity) {//有参构造
if (initialCapacity > 0) {
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
elementData=new Object[Default_initialization_capacity];
} else {
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}
public MyArrayList() {
elementData=new Object[Default_initialization_capacity];
}
//增加元素的方法
public void add(T o) {
dynamicMaintenanceArrayCapacity();
elementData[size] = o;
size++;
System.out.println("添加成功!");
}
//删除元素的方法
public void delete(int index) {
Object[] newAry = new Object[Default_initialization_capacity];
if (index < 0 || index >= size) {
System.out.println("删除失败!索引范围应为:(0 <--> " + (size - 1) + ")");
return;
} else {
if (index == 0) {
System.arraycopy(elementData, index + 1, newAry, index, elementData.length - index - 1);
} else {
System.arraycopy(elementData, 0, newAry, 0, index);
System.arraycopy(elementData, index + 1, newAry, index, elementData.length - index - 1);
}
}
size--;
elementData=newAry;
dynamicMaintenanceArrayCapacity();
System.out.println("删除成功!");
}
//修改元素的方法
public void update(int index, T value) {
if (index < 0 || index >= size) {
System.out.println("修改失败!索引范围应为:(0 <--> " + (size - 1) + ")");
} else {
elementData[index] = value;
System.out.println("修改成功!");
}
}
//获取元素的方法
public T getValueByIndex(int index) {
if (size==0){
System.out.println("当前集合是一个空集!");
return null;
}
if (index < 0 || index >= size) {
System.out.println("获取失败!索引范围应为:(0 <--> " + (size - 1) + ")");
return null;
} else {
System.out.println("获取成功!");
return (T)elementData[index];
}
}
//查询元素的方法
public int select(T t){
for (int i = 0; i < size; i++)
if (elementData[i] == t)
return i;
return -1;
}
//清空集合的方法
public void removeAll(){
size=0;
Default_initialization_capacity=10;
elementData=new Object[Default_initialization_capacity] ;
}
//扩容数组的方法
private void grow(int newCapacity) {
Object[] newAry = new Object[newCapacity];
if (size >= 0) System.arraycopy(elementData, 0, newAry, 0, size);
elementData = newAry;
Default_initialization_capacity = newAry.length;
}
private void dynamicMaintenanceArrayCapacity() {
if (size >= Default_initialization_capacity)
grow(elementData.length * 2);
if (size < Default_initialization_capacity / 2 && Default_initialization_capacity > 10) {
grow(Default_initialization_capacity / 2);
}
}
@Override
public String toString() {
int count=this.getSize();
StringBuilder stringBuffer = new StringBuilder();
if (count>=0){
stringBuffer.append("[");
for (int i = 0; i < count; i++) {
stringBuffer.append(elementData[i]).append(",");
}
stringBuffer.append("]");
return stringBuffer.toString();
}else
return "[]";
}
public int getSize() {
return size;
}
}
使用java基础,手工实现ArrayList集合。
最新推荐文章于 2024-08-30 18:40:43 发布