
public class MyArrayList {
public int[] elem;//数组
public int usedSize;//有效的数据个数
public static final int capacity = 10;//初始容量
public MyArrayList() {
this.elem = new int[capacity];
this.usedSize = 0;
}
//检查elem是否满了
private boolean isFull() {
if (this.usedSize == this.elem.length) {
return true;
}
return false;
}
//检查pos是否合法
private void checkPos(int pos) {
if (pos < 0 || pos > this.usedSize) {
throw new RuntimeException("pos位置不合法!");
}
}
//1.在pos位置插入元素
public void add(int pos, int data) {
//数组二倍扩容
if (isFull()) {
this.elem = Arrays.copyOf(this.elem, 2 * elem.length);
}
//检查pos是否合法
checkPos(pos);
//开始挪元素
for (int i = this.usedSize - 1; i >= pos; i-- ){
this.elem[i + 1] = this.elem[i];
}
this.elem[pos] = data;//插入元素
this.usedSize += 1;//有效元素个数+1
}
//2.打印顺序表
public void display(){
for (int i = 0;i < this.usedSize;i++) {
System.out.print(this.elem[i]+" ");
}
System.out.println();
}
//3.判定顺序表中是否包含某个元素
public boolean contains(int toFind) {
for (int i = 0;i < usedSize;i++){
if (this.elem[i] == toFind){
return true;
}
}
return false;
}
//4.查找某个元素对应的位置
public int search(int toFind) {
for (int i = 0;i < usedSize;i++){
if (this.elem[i]==toFind){
return i;
}
}
return -1;
}
//5. 获取pos位置的元素
public boolean isEmpty(){
return this.usedSize == 0;
}
public int getPos(int pos) {
//检查顺序表是否为空
if (isEmpty()){
throw new RuntimeException("顺序表为空");
}
//pos的合法性
if (pos < 0 || pos >= usedSize){
throw new RuntimeException("pos位置不合法!");
}
return this.elem[pos];
}
//6.获取顺序表长度
public int size() {
return this.usedSize;
}
//7.删除第一次出现的关键字key
public void remove(int toRemove) {
//判断是否有key
if (search(toRemove) == -1) {
System.out.println("没有需要删除的数字");
return;
}
for (int i = this.getPos(toRemove); i < this.usedSize - 1; i++) {
this.elem[i] = this.elem[i + 1];
}
this.usedSize--;
}
//8.清空顺序表
public void clear(){
this.usedSize = 0;
}
//9.把pos位置的元素设置为value
public void setPos(int pos,int value) {
if (pos < 0 || pos >= usedSize){
throw new RuntimeException("pos位置不合法!");
}
this.elem[pos] = value;
}
}
上一篇 Android 内存优化 - OnTrimMemory优化
下一篇 ERROR: Could not build wheels for numpy which use PEP 517 and cannot be installed directly