这篇文章给大家分享的是有关怎么用Java实现顺序表的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

一、什么是顺序表?

顺序表就是按照顺序存储方式存储的线性表,该线性表的结点按照逻辑次序依次存放在计算机的一组连续的存储单元中。

由于顺序表是依次存放的,只要知道了该顺序表的首地址及每个数据元素所占用的存储长度,那么就很容易计算出任何一个数据元素(即数据结点)的位置。

二、顺序表的常见操作:

1、创建类和构造方法

publicclassMyArrayList{

privateint[]elem;

privateintusedSize;

publicMyArrayList(){

this.elem=newint[10];

}

publicMyArrayList(intcapacity){

this.elem=newint[capacity];

}

}

2、扩容

publicvoidresize(){

this.elem=Arrays.copyOf(this.elem,2*this.elem.length);

}

3、判断顺序表是否为满

publicbooleanisFull(){

if(this.usedSize==this.elem.length){

returntrue;

}

returnfalse;

}

4、打印顺序表

publicvoiddisplay(){

for(inti=0;i<usedSize;i++){

System.out.print(elem[i]+"");

}

System.out.println();

}

5、在 pos 位置新增元素

publicvoidadd(intpos,intdata){

if(isFull()){

System.out.println("链表已满!");

resize();

}

if(pos<0||pos>this.usedSize){

System.out.println("插入位置不合法!");

return;

}

for(inti=usedSize-1;i>=pos;i--){

elem[i+1]=elem[i];

}

elem[pos]=data;

this.usedSize++;

}

6、判断是否包含某个元素

publicbooleancontains(inttoFind){

for(inti=0;i<usedSize;i++){

if(elem[i]==toFind){

returntrue;

}

}

returnfalse;

}

7、查找某个元素对应的位置

publicintsearch(inttoFind){

for(inti=0;i<usedSize;i++){

if(elem[i]==toFind){

returni;

}

}

return-1;

}

8、获取 pos 位置的元素

publicintgetPos(intpos){

if(pos<0||pos>=usedSize){

System.out.println("该pos位置不合法!");

return-1;

}

returnelem[pos];

}

9、给 pos 位置的元素修改为 value

publicvoidsetPos(intpos,intvalue){

if(pos<0||pos>=usedSize){

System.out.println("该pos位置不合法!");

return;

}

elem[pos]=value;

}

10、删除第一次出现的关键字 Key

publicvoidremove(inttoRemove){

intindex=-1;

for(inti=0;i<this.usedSize;i++){

if(this.elem[i]==toRemove){

index=i;

}

}

if(index==-1){

System.out.println("未找到该元素!");

return;

}

for(intj=index;j<this.usedSize-1;j++){

this.elem[j]=this.elem[j+1];

}

this.usedSize--;

}

11、获取链表长度

publicintsize(){

returnthis.usedSize;

}

12、清空顺序表

publicvoidclear(){

this.usedSize=0;

}

感谢各位的阅读!关于“怎么用Java实现顺序表”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!