1. 程式人生 > >java建立順序表及增刪改查功能實現

java建立順序表及增刪改查功能實現

順序表類的增刪改查功能實現java語言描述
package ch01;

public class Sqlist {
	private Object listelem[];          //線性表儲存空間
	private int curlen;                 //線性表當前長度
	public Sqlist(int maxsize){
		curlen=0;                       //置順序表長度為0
		listelem=new Object[maxsize];   //為順序表分配maxsize個儲存單元
	}
	public void clear(){                 //將一個已存在的順序表置成空表
		curlen=0;
	}
	public boolean isEmpty(){             //判斷順序表中資料元素個數是否為0,若為0返回true否則返回false
		return curlen==0;
	}
	public int length(){               //求順序表中資料元素個數並返回其值
		return curlen;
	}
	public Object get(int i)throws Exception{    //查詢順序表第i個位置元素並返回其值
		if(i<0||i>curlen)
			throw new Exception("查詢位置不合理");
		return listelem[i];
	}
	public void insert (int i,Object x)throws Exception{    //在順序表中第i個位置元素之前插入值為x的元素
		if(curlen==listelem.length)
			throw new Exception("順序表已滿");
		if(i<0||i>curlen)
			throw new Exception("插入位置不合理");
		for(int j=curlen;j>i;j--)
		    listelem[j]=listelem[j-1];
		listelem[i]=x;
		curlen++;
	}
	public void remove(int i)throws Exception{           //刪除順序表第i個位置的元素
		if(i<0||i>curlen-1)
			throw new Exception("刪除位置不合理");
		for(int j=i;j<curlen;j++)
			listelem[j]=listelem[j+1];
		curlen--;
	}
	public void display(){                       //輸出順序表中的資料元素
		for(int i=0;i<curlen;i++)
			System.out.println(listelem[i]);
	}
	public int indexof(Object x){                //返回順序表中首次出現指定資料元素的位序號
		int j=0;
		while(j<curlen&&!listelem[j].equals(x)){
			j++;
		}
		if(j<curlen)
		return j;
		else 
			return -1;
	}
	public static void main(String[] args)throws Exception{
		Sqlist L=new Sqlist(10);                  //構造一個含有10個儲存單元的儲存空間的空順序表
	     L.insert(0, 'a');
	     L.insert(1, 'z');
	     L.insert(2, 'd');
	     L.insert(3, 'm');
	     L.insert(4, 'z');
		 L.display();
		 int order=L.indexof('z');
		 if(order!=-1)
			 System.out.println("順序表中第一次出現z資料元素的位置"+order);
		 else {
			System.out.println("此順序表中不包含值為z的資料元素");
		}
		 System.out.println("查詢表中第3個位置元素值:");
			System.out.println(L.get(3));
			System.out.println("刪除表中第3個位置元素值");
			L.remove(3);
			System.out.println("刪除成功");
			System.out.println("剩餘元素值");
			L.display();
	}

}

在myeclipse中,可能會出現不支援泛型的問題
解決方案:專案名稱上右擊,properties然後找到java compiler 版本不能低於1.5,改為1.6的就可以了。