ArrayList的基本方法

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--;
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值