话不多说,直接上代码
package com.mydemo.writeCases;
import java.util.Objects;
public class IArrayList<T>{
private T[] array;
private int size;
IArrayList(int capacity){
this.array = (T[]) new Object[capacity];
}
IArrayList(){
this(10);
}
public int getSize(){
return size;
}
public void add(T t) {
add(t,size);
}
public void add(T t,int index) {
if (index < 0 || index > size) {
throw new IndexOutOfBoundsException("角标越界");
}
if (size == this.array.length){
resize();
}
System.arraycopy(array,index,array,index+1,size-index);
this.array[index] = t;
size++;
}
public boolean isEmpty(){
return this.size == 0;
}
private void resize(){
int newLength = array.length * 2 + 1;
T[] newArray = (T[]) new Object[newLength];
System.arraycopy(array,0,newArray,0,size);
array = newArray;
}
public T get(int index){
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("角标越界");
}
return array[index];
}
public void set(T t,int index){
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("角标越界");
}
array[index] = t;
}
public T remove(int index){
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("角标越界");
}
T targetElement = array[index];
for (int i = index; i < size-1; i++) {
array[i] = array[i+1];
}
array[size-1] = null;
size--;
return targetElement;
}
public boolean remove(Object o) {
for (int i = 0; i < size; i++) {
if (Objects.equals(array[i],o)) {
remove(i);
return true;
}
}
return false;
}
@Override
public String toString(){
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size; i++) {
sb.append("[" + (array[i] == null ? "null" : array[i].toString()) + "]");
}
return sb.toString();
}
}