public class MyArray<E> {
//泛型数组
private E[] data;
//数组的容量
private int size;
//删除数组元素
private E remove(int index){
if(index<0||index>=0){
throw new IllegalArgumentException
("Remove failed. Index is illegal.");
}
E ret=data[index];
for(int i=index+1;i<size;i++){
data[i-1]=data[i];
}
size--;
if(size == data.length / 2)
resize(data.length / 2);
return ret;
}
//在数组中添加一个元素
// 构造函数,传入数组的容量capacity构造Array
public MyArray(int capacity){
data = (E[])new Object[capacity];
size = 0;
}
// 无参数的构造函数,默认数组的容量capacity=10
public MyArray(){
this(10);
}
//从数组中删除第一个元素,返回删除的元素
public E RemoveFirst(){
return remove(0);
}
//删除数组最后一个元素,返回删除的元素
public E RemoveLast(){
return remove(size-1);
}
//向数组index位置添加元素e
public void add(int index,E e){
if(size==data.length)
throw new IllegalArgumentException
("add last is failed.array is full");
if(index<0||index>size){
throw new IllegalArgumentException
("add last is failed.array is full");
}
for(int i=size-1;i>=index;i--) {
data[i+1]=data[i];
}
data[index]=e;
size++;
}
//向数组末尾添加元素e
public void addLast(E e){
if(size==data.length)
throw new IllegalArgumentException
("add last is failed.array is full");
data[size]=e;
size++;
}
//获取index索引位置的元素
E get(int index){
return data[index];
}
//删除数组中的元素e
public void delete(E e){
for(int i=0;i<size;i++){
if(data[i].equals(e)){
for(int t=i;t<size;t++,i++){
data[t]=data[i+1];
}
size--;
}
}
}
//查找数组中的某元素
public int find(E e){
for(int i=0;i<size;i++){
if(data[i].equals(e))
return i;
}
return -1;
}
//查找数组中的全部某元素e
public void findAll(E e){
int num=0;
for(int i=0;i<size;i++){
if(data[i].equals(e))
System.out.println(i);
num++;
}
System.out.println(num);
}
//获取数组的容量
public int getCapacity(){
return data.length;
}
//获取数组中元素的个数
public int getSize(){
return size;
}
//将数组变换为newCapacity大小
public void resize(int newCapacity){
E[] newData = (E[])new Object[newCapacity];
for(int i = 0 ; i < size ; i ++)
newData[i] = data[i];
data = newData;
}
//判断数组是否为空
public boolean isEmpty(){
return size==0;
}
@Override
public String toString(){
StringBuilder res=new StringBuilder();
res.append("[");
for(int i=0;i<size;i++){
res.append(data[i]);
if(i!=size-1)
res.append(",");
}
res.append("]");
return res.toString();
}
}