public class Array<E> {
public static void main(String[] args) {
Array<Integer> array = new Array<>(5);
array.add(6);
array.add(87);
array.add(63);
array.add(13);
array.delete(0);
array.delete(0);
array.display();
}
private static final int DEFAULT_CAPACITY = 10;
private static final int RESIZE_RATE = 2;
int size;
int capacity;
E[] data;
public Array(int capacity) {
data = (E[]) new Object[capacity];
this.capacity = capacity;
this.size = 0;
}
public Array() {
this(DEFAULT_CAPACITY);
}
void add(E e){
if(size >= capacity){
resize(capacity*RESIZE_RATE);
capacity = capacity*RESIZE_RATE;
}
data[size++] = e;
}
private void insert(int index,E e){
if(size >= capacity){
resize(capacity*RESIZE_RATE);
capacity = capacity*RESIZE_RATE;
}
if (index<=size && index>=0) {
for (int i = size-1; i >= index; i--) {
data[i+1] = data[i];
}
data[index] = e;
size++;
}else {
throw new IllegalArgumentException("插入失败");
}
}
private void delete(int index){
if (index<=size && index>=0){
data[index] = null;
for (int i = index+1; i < size; i++) {
data[i-1] = data[i];
}
}
if (size < capacity/2){
resize(capacity/RESIZE_RATE);
capacity = capacity/RESIZE_RATE;
}
size--;
}
public void display() {
System.out.print("Data:");
for (int i = 0 ; i < size; i++) {
System.out.print(data[i] + " ");
}
System.out.println();
System.out.println("Capacity="+capacity);
}
public void resize(int newCapacity){
E[] temp = (E[]) new Object[newCapacity];
for (int i = 0; i < size; i++) {
temp[i] = data[i];
}
data = temp;
}
}
数组实现原理
最新推荐文章于 2022-12-09 23:06:13 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)