记录
public class MyArrayList {
public static void main(String[] args) {
MyArrayList myArrayList = new MyArrayList();
myArrayList.add(0, 1);//在 pos 位置新增元素
myArrayList.add(1, 2);
myArrayList.add(2, 3);
myArrayList.add(3, 4);
myArrayList.display();
System.out.println("==================");
System.out.println(myArrayList.contains(4));// 判定是否包含某个元素
System.out.println(myArrayList.search(4));//查找某个元素对应的位置
System.out.println(myArrayList.getPos(3));//获取 pos 位置的元素
myArrayList.setPos(3,11);//给 pos 位置的元素设为 value
myArrayList.display();
System.out.println("==================");
myArrayList.remove(11);
myArrayList.display();
System.out.println("==================");
System.out.println(myArrayList.size()); // 获取顺序表长度
myArrayList.clear();// 清空顺序表
System.out.println("==================");
myArrayList.display();
}
public int[] elem;
public int usedSize;
public MyArrayList(){
this.elem = new int[5];
}
//打印顺序表
public void display() {
for (int i = 0; i < this.usedSize; i++) {
System.out.print(this.elem[i]+" ");
}
System.out.println();
}
//在 pos 位置新增元素
public void add(int pos,int data){
//先判断链表满了没有
if(this.usedSize == this.elem.length){
System.out.println("顺序表满了!,需要扩容!");
this.elem = Arrays.copyOf(this.elem,2*this.elem.length);
}
//再判断pos的合法性
if(pos < 0 || pos >this.usedSize ){
System.out.println("pos位置不合法!");
return;
}
//开始移动
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 = 0; i < this.usedSize; i++) {
if(this.elem[i] == toFind){
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 >this.usedSize-1 ){
System.out.println("pos位置不合法!");
}
return this.elem[pos];
}
//给 pos 位置的元素设为 value
public void setPos(int pos, int value){
if(pos < 0 || pos >this.usedSize-1 ){
System.out.println("pos位置不合法!");
}
this.elem[pos] = value;
}
//删除第一次出现的关键字key
public void remove(int key){
int index = search(key);
if(index == -1){
System.out.println("你要删除的关键字" + key + "不存在" );
return;
}
for (int i = index; 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;
}
}
运行结果