import java.util.Arrays;
public class ArrayList {
public int[] array = new int[100];
public int usedSize;
public ArrayList() {
this.array = array;
this.usedSize = usedSize;//实际使用长度
}
//打印顺序表
public void display() {
for (int i = 0; i < this.usedSize; i++) {
System.out.print(array[i] + " ");
}
System.out.println();
}
//往pos位置添加元素
public void add(int pos, int data) {
//1.先判断是否满了,如果满了扩容
if (isFull()){
this.array = Arrays.copyOf(this.array,2*this.array.length);
}
//2.pos位置是否合法
if (pos < 0 || pos > this.usedSize){
return;
}
//3.把pos位置以后的元素每个都往后挪一格
for (int i = usedSize - 1; i >= pos; i--) {
array[i + 1] = array[i];
}
//4.将data赋值给pos位置
array[pos] = data;
usedSize++;
}
private boolean isFull(){
if (this.usedSize == this.array.length) {
return true;
}
return false;
}
// 判定是否包含某个元素
public boolean contains(int toFind){
for (int i = 0; i < this.usedSize ; i++) {
if (array[i] == toFind){
return true;
}
}
return false;
}
//查找找某个元素对应的位置
public int search(int toFind) {
for (int i = 0; i < this.usedSize; i++) {
if (array[i] == toFind){
return i;
}
}
return -1;
}
// 获取 pos 位置的元素
public int getPos(int pos){
if (pos < 0 || pos > this.usedSize){
return -1;
}
return array[pos];
}
// 给 pos 位置的元素设为 value
public void setPos(int pos, int value){
if (pos < 0 || pos > this.usedSize){
return;
}
System.out.println(array[pos] = value);
}
//删除第一次出现的元素
public void remove(int toRemove) {
int index = search(toRemove);
if (index == -1){
return;
}
for (int i = index; i < this.usedSize-1 ; i++) {
this.array[i] = this.array[i+1];
}
this.usedSize--;
}
}