package Data;
import java.util.Arrays;
public class ArrayPlus<T> {
private T[] data;
private int size;
public ArrayPlus(int capacity) {
this.data = (T[]) new Object[capacity];
this.size = 0;
}
public ArrayPlus() {
this(10);
}
public int getSize() {
return this.size;
}
public int getLength() {
return this.data.length;
}
public boolean isEmpty() {
return this.size == 0;
}
public void add(T e) {
add(size, e);
}
public void addFirst(T e) {
add(0, e);
}
public void add(int index, T e) {
checkIndexForAdd(index);
if (size == data.length) {
resize(2 * data.length);
}
for (int i = size - 1; i >= index; i--) {
data[i + 1] = data[i];
}
this.data[index] = e;
size++;
}
public boolean contains(T e) {
for (int i = 0; i < size; i++) {
if (data[i].equals(e)) {
return true;
}
}
return false;
}
public void addPlus(int index, T e) {
checkIndexForAdd(index);
if (size == data.length) {
resize(2 * data.length);
}
this.data[size++] = this.data[index];
this.data[index] = e;
}
public T remove(int index) {
checkIndex(index);
T ret = data[index];
for (int i = index + 1; i < size; i++) {
data[i - 1] = this.data[i];
}
size--;
data[size] = null;
if (size <= data.length / 2) {
resize(data.length / 2);
}
return ret;
}
public T get(int index) {
checkIndex(index);
return this.data[index];
}
private void resize(int newSize) {
T[] newArray = (T[]) new Object[newSize];
for (int i = 0; i < size; i++) {
newArray[i] = this.data[i];
}
this.data = newArray;
}
private void checkIndex(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("error!!! 下標越界");
}
}
private void checkIndexForAdd(int index) {
if (index < 0 || index > size) {
throw new IndexOutOfBoundsException("error!!! 下標越界");
}
}
@Override
public String toString() {
return "ArrayPlus{" +
"data=" + Arrays.toString(data) +
", size=" + size +
'}';
}
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結