Make a generic vector in Java

Asked

Viewed 2,344 times

6

How to create a dynamic vector in Java with generic programming? This vector must have initial size 4 and be increased in size as new elements need to be inserted.

The class must have:

  • Constructor.
  • Constructor with initial vector size parameter
  • bool remove (element)
  • bool add(Element)
  • first element()
  • last element()
  • bool search(element)
  • int size()
  • string print().

What I’ve done so far:

package atividade;

public class Vetor<T> {

    T[] vetor;
    int qntElementos = 0;
    public Vetor(int tam) {
        vetor = (T[]) new Object[tam];
    }
    public boolean vazio() {
        return Tamanho() == 0;
    }
    public void Adicionar(T elemento) {
        if (Tamanho() == vetor.length) {
            redimensionar();
        }
        for (int i = 0; i < vetor.length; i++) {
            if (vetor[i] == null) {
                vetor[i] = (T) elemento;
                qntElementos++;
                break;
            }
        }
    }

    public void Remover(int posicao) throws ArrayIndexOutOfBoundsException {
        if (vazio()) {
            throw new ArrayIndexOutOfBoundsException("Vazio");
        }
        if (posicao < vetor.length) {
            vetor[posicao] = null;
            qntElementos--;
        } else {
            System.out.println("Posição inexistente!!!");
        }
    }

    public void RemoverInicio() {
        if (vazio()) {
            System.out.println("Vetor vazio!");
        }
        for (int i = 0; i < vetor.length; i++) {
            if (vetor[i] != null) {
                vetor[i] = null;
                break;
            }
            qntElementos--;
        }
    }

    public void RemoverFim() {
        if (vazio()) {
            System.out.println("Vetor vazio!");
        }
        for (int i = 0; i < vetor.length; i++) {
            if (vetor[i] == null) {
                vetor[i - 1] = null;
            }
            qntElementos--;
            break;
        }
        vetor[Tamanho()] = null;
    }

    public int Tamanho() {
        return qntElementos;
    }

    public void Limpar() {
        for (int i = 0; i < vetor.length; i++) {
            if (vetor[i] != null) {
                vetor[i] = null;
                qntElementos--;
            }
        }
    }

    public void redimensionar(){
        T[] novoVetor = (T[]) new Object[vetor.length * 2];
        if(vetor.length == Tamanho()){
            for(int i =0; i < vetor.length; i++){
                novoVetor[i] = vetor[i];
            }
            vetor = novoVetor;
        }
    }
}
  • 1

    What have you done? What specific question do you have?

  • What’s the matter?

  • I think here vetor = (T[]) new Object[tam]; the correct would be vetor = new T[tam];, since T will be an Object, but not always the opposite will be true.

  • 1

    @Diegof also found, but Java does not allow this.

1 answer

4


I have improved and solve some problems, many even syntax. I made some extra methods, which were in the statement and others that might be useful. I adopted the typical Java style, but did not change the names of methods and functions that I think are not the best. And I did some things that I think are more appropriate in each situation. Normally I would improve other things, but I already moved too much. I can’t guarantee that everything is okay, but I did a basic test. Obviously the implementation is a little naive.

I would like Java to have a better way of dealing with genericity. It has even improved a little with reflection that I preferred to avoid. At least I used Comparable in place of Object to limit a little more.

class Vector<T> {
    T[] vetor;
    int qntElementos = 0;
    public Vector(int tam) {
        vetor = (T[]) new Comparable[tam];
    }
    public Vector() {
        this(4);
    }
    public void adicionar(T elemento) {
        if (tamanho() == vetor.length) redimensionar();
        vetor[tamanho()] = elemento;
        qntElementos++;
    }
    public T pegar(int posicao) {
        if (vazio() || posicao < 0 || posicao >= tamanho()) throw new ArrayIndexOutOfBoundsException("Posição fora da faixa permitida");
        return vetor[posicao];
    }
    public T pegarPrimeiro() {
        if (vazio()) throw new ArrayIndexOutOfBoundsException("Posição fora da faixa permitida");
        return vetor[0];
    }
    public T pegarUltimo() {
        if (vazio()) throw new ArrayIndexOutOfBoundsException("Posição fora da faiza permitida");
        return vetor[qntElementos - 1];
    }
    public int procurar(T elemento) {
        for (int i = 0; i < qntElementos; i++) {
            if (vetor[i].equals(elemento)) return i;
        }
        return -1;
    }
    public boolean removerElemento(T elemento) {
        return remover(procurar(elemento));
    }
    public boolean remover(int posicao) {
        if (!vazio() && posicao >= 0 && posicao < tamanho()) {
            for (int i = posicao; i < qntElementos; i++) vetor[i] = vetor[i + 1];
            vetor[tamanho()] = null;
            qntElementos--;
            return true;
        } else {
            return false;
        }
    }
    public boolean removerInicio() {
        if (vazio()) return false;
        for (int i = 0; i < qntElementos; i++) vetor[i] = vetor[i + 1];
        qntElementos--;
        return true;
    }
    public boolean removerFim() {
        if (vazio()) return false;
        vetor[tamanho()] = null;
        qntElementos--;
        return true;
    }
    public int tamanho() {
        return qntElementos;
    }
    public boolean vazio() {
        return tamanho() == 0;
    }
    public void limpar() {
        vetor = (T[]) new Comparable[4];
    }
    private void redimensionar() {
        T[] novoVetor = (T[]) new Comparable[vetor.length * 2];
        if (vetor.length == tamanho()) {
            for (int i = 0; i < vetor.length; i++) novoVetor[i] = vetor[i];
            vetor = novoVetor;
        }
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Thank you very much, already helped me mto.. how do I get the first and last element of the list? and do a binary search of a list element?

  • @Carlosdiego I changed what was in the question. The binary search was not. It would be good to ask another question. You’d have to make sure the vector is ordered to do the binary search. What’s kind of weird to do, the ideal ), but not mandatory) is to have a completely different structure. Take a look at [tour], now you can vote on everything on the site.

  • @bigown, it would be possible, rather than rewriting everything, to inherit from Collection and overwrite only the methods it does not have, while maintaining a generic list ?

  • @Paulogustavo Seria. That’s what I would do. But all the methods would have to be written since Collection is an interface, so there is no implementation of the methods, only the contracts. There are several improvements that could be made in this class if it were actually used. It just doesn’t make much sense. In the background this class is reimplementando a ArrayList. It’s only interesting to do this as an exercise.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.