数据结构之动态数组

package cn.Arrays.lpq;

public class Array1 {
private int [] data;
private int size;
//有参构造,确定数组容量为capacity
public Array1(int capacity){
data=new int[capacity];
size=0;
}
//无参构造,默认数组容量为10;
public Array1(){
this(10);
}
//获取数组容量
public int getCapacity(){
return data.length;
}
//获取数组中元素的个数
public int getSize(){
return size;
}
//判断数组是否为空
public boolean isEmpty(){
return size==0;
}
//在元素的最后位置添加元素
public void addLast(int e){
if(size==data.length){
throw new IllegalArgumentException(“数组已经添加满了”);
}
data[size]=e;
size++;
}
//在数组的第一个位置上添加元素
public void addFirst(int e){
if(size==data.length){
throw new IllegalArgumentException(“数组已经添加满了”);
}
for(int i=size-1;i>=0;i–){
data[i+1]=data[i];
}
data[0]=e;
size++;
}
//在数组中的任意位置添加元素
public void add(int index,int e){
if(size==data.length){
throw new IllegalArgumentException(“数组已经添加满了”);
}
if(index<0 || index>size){
throw new IllegalArgumentException(“该索引位置不可以插入元素!”);
}
for(int i=size-1;i>=index;i–){
data[i+1]=data[i];

    }
    data[index]=e;
    size++;

}

}

猜你喜欢

转载自blog.csdn.net/lpq1201/article/details/79997411