import java.util.Arrays;
public class MyArraylist {
int[] element;
int size;
public MyArraylist() {
this.size=0;
this.element=new int[4];
}
public MyArraylist(int capacity) {
this.size=0;
this.element=new int[capacity];
}
public void display() {
for (int i=0;i<this.size;i++){
System.out.print(this.element[i]+" ");
}
System.out.println();
}
public boolean isFull() {
if (this.size==this.element.length){
return true;
}
return false;
}
public void resize( ) {
this.element= Arrays.copyOf(this.element,2*this.element.length);
}
public void addPos(int pos, int data) {
if (pos<0||pos>this.element.length-1){
System.out.println("插入位置不合法");
return;
}
if (isFull()){
resize();
}
for (int i=this.size-1;i>=pos;i--){
this.element[i+1]=this.element[i];
}
this.element[pos]=data;
this.size++;
}
public void addTail(int data) {
if (isFull()){
resize();
}
this.element[this.size]=data;
this.size++;
}
public boolean contains(int toFind) {
for (int i=0;i<this.size;i++){
if (this.element[i]==toFind){
return true;
}
}
return false;
}
public int search(int toFind) {
for (int i=0;i<this.size;i++) {
if (this.element[i] == toFind) {
return i;
}
}
return -1;
}
public int size() {
return this.size;
}
public int getPos(int pos) {
if (pos<0||pos>this.size-1){
System.out.println("查詢位置不合法");
}
return this.element[pos];
}
public void setPos(int pos, int value) {
if (pos<0||pos>this.size-1){
System.out.println("修改位置不合法");
}
this.element[pos]=value;
}
public void remove(int key) {
int index=search(key);
for (int i=index;i<this.size;i++){
this.element[i]=this.element[i+1];
}
this.size--;
}
public void clear() {
this.size=0;
}
public static void main(String[] args) {
MyArraylist myArraylist=new MyArraylist(4);
myArraylist.addPos(0,10);
myArraylist.addPos(1,20);
myArraylist.addPos(2,30);
myArraylist.display();
myArraylist.addTail(40);
myArraylist.display();
myArraylist.addTail(50);
myArraylist.display();
myArraylist.addPos(2,60);
myArraylist.display();
int index=myArraylist.search(60);
System.out.println("查詢元素的位置:"+index);
boolean bool=myArraylist.contains(60);
System.out.println("查詢元素是否存在:"+bool);
int val=myArraylist.getPos(2);
System.out.println("獲取指定位置元素:"+val);
myArraylist.setPos(2,70);
myArraylist.display();
int size=myArraylist.size();
System.out.println("線性表的大小:"+size);
myArraylist.remove(70);
myArraylist.display();
myArraylist.clear();
size=myArraylist.size();
System.out.println("清空線性表後的大小:"+size);
myArraylist.display();
}
}
- 測試用例