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;
        }
    }
}
						
What have you done? What specific question do you have?
– Maniero
What’s the matter?
– Maniero
I think here
vetor = (T[]) new Object[tam];the correct would bevetor = new T[tam];, since T will be an Object, but not always the opposite will be true.– user28595
@Diegof also found, but Java does not allow this.
– Maniero