Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

How to implement a sequential table with Java


May 30, 2021 Article blog


Table of contents


What is a sequential table?

A sequential table is a linear table stored sequentially, where the nodes of a linear table are stored in logical order in a continuous set of storage units on a computer.

Because the sequential tables are stored in turn, it is easy to calculate the location of any one data element (that is, the data node) as long as you know the first address of the sequential table and the storage length occupied by each data element.

Second, the common operation of sequential tables:

1, create classes and construction methods

public class MyArrayList {

private int [] elem;

private int usedSize;

public MyArrayList(){

this.elem = new int [10];

}

public MyArrayList(int capacity){

this.elem = new int[capacity];

}

}


2, expand capacity

public void resize(){

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

}


3, to determine whether the order table is full

public boolean isFull(){

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

return true;

}

return false;

}


4, print the order table

public void display() {

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

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

}

System.out.println();

}


5, add elements at pos position

public void add(int pos, int data) {

if(isFull()){

System.out.println ("Link list is full!");

resize();

}

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

System.out.println ("Insert Location is not legal!");

return;

}

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

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

}

elem[pos] = data;

this.usedSize++;

}


6, to determine whether an element is included

public boolean contains(int toFind) {

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

if(elem[i] == toFind){

return true;

}

}

return false;

}


7, find the location of an element

public int search(int toFind) {

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

if(elem[i] == toFind){

return i;

}

}

return -1;

}


8, get the element of the pos position

public int getPos(int pos) {

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

System.out.println ("This POS location is not legal!");

return -1;

}

return elem[pos];

}


9. Modify the element in the pos position to value

public void setPos(int pos, int value) {

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

System.out.println ("This POS location is not legal!");

return;

}

elem[pos] = value;

}


10, delete the keyword Key that first appeared

public void remove(int toRemove) {

int index = -1;

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

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

index = i;

}

}

if(index == -1){

System.out.println ("Not finding this element!");

return;

}

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

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

}

this.usedSize--;

}


11, get the chain length

public int size() {

return this.usedSize;

}


12, empty the order table

public void clear() {

this.usedSize = 0;

}