import java.util.Arrays;
class MyArrayList {
//属性
private int[] elem;
private int usedSize;//有效数据的个数
private final int CAPACITY = 5;//容量
public MyArrayList() {//构造方法
this.elem = new int[CAPACITY];
this.usedSize = 0;
}
//方法
// 打印顺序表
public void display() {
for (int i = 0; i < this.usedSize; i++) {
System.out.print(this.elem[i] + " ");
}
System.out.println();
}
private boolean isfull() {
return this.elem.length == this.usedSize;
}
// 在 pos 位置新增元素
public void add(int pos, int data) {
if (isfull()) {
this.elem = Arrays.copyOf(this.elem, this.elem.length * 2);
}//数组拷贝 2倍
if (pos < 0 || pos > this.usedSize) {
System.out.println("该位置不合法");
}
//挪数据
for (int i = this.usedSize - 1; i >= pos; i--) {
this.elem[i + 1] = this.elem[i];
}
this.elem[pos] = data;
this.usedSize++;
}
// 判定是否包含某个元素
public boolean contains(int toFind) {
for (int i = this.usedSize; i >= 0; i--) {
if (toFind == this.elem[i]) {
return true;
}
}
return false;
}
// 查找某个元素对应的位置
public int search(int toFind) {
for (int i = 0; i < this.usedSize; i++) {
if (this.elem[i] == toFind) {
return i;
}
}
return -1;
}
// 获取 pos 位置的元素
public int getPos(int pos) {
if (pos < 0 || pos > usedSize) {
return -1;//没有pos位置
}
return this.elem[pos];
}
// 给 pos 位置的元素设为 value
public void setPos(int pos, int value) {
this.elem[pos] = value;
}
//删除第一次出现的关键字key
public void remove(int toremove) {
int a = search(toremove);
if (a == -1) {
System.out.println("找不到要删除的数字");
}
for (int i = a; i < this.usedSize - 1; i++) {
this.elem[i] = this.elem[i + 1];
}
this.usedSize--;
}
// 获取顺序表长度
public int size() {
return this.usedSize;
}
// 清空顺序表
public void clear() {
this.usedSize = 0;
}
}
public class Test2 {
public static void main(String[] args) {
MyArrayList myArrayList= new MyArrayList();
myArrayList.add(0,12);
myArrayList.add(1,23);
myArrayList.add(2,34);
myArrayList.add(3,45);
myArrayList.add(4,56);
//myArrayList.add(5,90);
int sum = myArrayList.search(90);
System.out.println(sum);
myArrayList.remove(23);
//myArrayList.remove(6);
myArrayList.display();
int L = myArrayList.size();
System.out.println(L);
myArrayList.clear();//清空
myArrayList.display();
}
}
==========================================
输出结果:
-1
12 34 45 56
4
java 顺序表 增删改查
最新推荐文章于 2022-10-10 01:11:18 发布