Java List Implementation with Search, Insert, and Remove
Classified in Technology
Written at on English with a size of 2.3 KB.
Java List Implementation
Class Definition
public class Lista {
private Object[] item;
private int primeiro, ultimo, pos;
public Lista(int maxTam) {
this.item = new Object[maxTam];
this.pos = -1;
this.primeiro = 0;
this.ultimo = this.primeiro;
}
}
Search Method
public Object pesquisa(Object chave) {
if (this.vazia() || chave == null) {
return null;
}
for (int p = 0; p < this.ultimo; p++) {
if (this.item[p].equals(chave)) {
return this.item[p];
}
}
return null;
}
Insert Method
public void insere(Object x) {
if (this.ultimo >= this.item.length) {
throw new Exception("Error: List is full");
} else {
this.item[this.ultimo] = x;
this.ultimo++;
}
}
Remove Method
public Object retira(Object chave) {
if (this.vazia() || chave == null) {
throw new Exception("Error: List is empty");
}
int p = 0;
while (p < this.ultimo && !this.item[p].equals(chave)) {
p++;
}
if (p >= this.ultimo) {
return null; // Key not found
}
Object item = this.item[p];
this.ultimo--;
for (int aux = p; aux < this.ultimo; aux++) {
this.item[aux] = this.item[aux + 1];
}
return item;
}
Remove First Method
public Object retiraPrimeiro() {
if (this.vazia()) {
throw new Exception("Error: List is empty");
}
Object item = this.item[0];
this.ultimo--;
for (int aux = 0; aux < this.ultimo; aux++) {
this.item[aux] = this.item[aux + 1];
}
return item;
}
First and Next Methods
public Object primeiro() {
this.pos = -1;
return this.proximo();
}
public Object proximo() {
this.pos++;
if (this.pos >= this.ultimo) {
return null;
} else {
return this.item[this.pos];
}
}
Empty and Print Methods
public boolean vazia() {
return (this.primeiro == this.ultimo);
}
public void imprime() {
for (int aux = this.primeiro; aux < this.ultimo; aux++) {
System.out.print(this.item[aux].toString() + " ");
}
}