Why can’t I print the values of a chained list?

Asked

Viewed 48 times

3

I need to generate an empty chained list and do three operations with it:

  1. Add an element to the end of the list
  2. Remove an item from the list
  3. Insert n elements at the end of the list

Finally, the elements must be objects of a class Elemento. This way I created the class Elemento:

public class Elemento {

    private int valor;
    private int proximo = 0;

    Elemento(int pValor) {
        valor = pValor;
        proximo++;
    }
}

The class of the list:

public class MinhaListaEncadeada {

    private ArrayList<Elemento> ListaEncadeada;
    private Elemento elemento;

    MinhaListaEncadeada() {
        ListaEncadeada = new ArrayList();
    }

    public void inserirElemento(int pValor) {
        ListaEncadeada.add(new Elemento(pValor));
    }

    public void removeElemento(int pValor) {
        for (int i=0; i<ListaEncadeada.size(); i++) {
            elemento = ListaEncadeada.get(i);
            if (elemento.equals(pValor))
                ListaEncadeada.remove(elemento);
        }        
    }

    public void insereNElementos(int n) {
        for (int i=1; i<n+1; i++)
            ListaEncadeada.add(new Elemento(i));
    }

    public void imprimeLista() {
        for (int i=0; i<ListaEncadeada.size(); i++) {
            if (i < ListaEncadeada.size()-1)
                System.out.print(ListaEncadeada.get(i) + ", ");
            else
                System.out.println(ListaEncadeada.get(i));
            }
        }
}

And finally I called your methods in main with some tests:

public class Exercicio3ListaEncadeada {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        MinhaListaEncadeada lista = new MinhaListaEncadeada();
        Elemento e;

        System.out.print("\n Inserindo o elemento 6 no final da lista: \n");
        lista.inserirElemento(6);
        lista.imprimeLista();

        System.out.print("\n Inserindo 6 elementos na lista: \n");
        lista.insereNElementos(6);
        lista.imprimeLista();

        System.out.print("\n Removendo o valor 4 na lista: \n");
        lista.removeElemento(4);
        lista.imprimeLista();
    }

}

But every time I run the program it returns:

Inserindo o elemento 6 no final da lista: 
exercicio3listaencadeada.Elemento@7229724f

 Inserindo 6 elementos na lista: 
exercicio3listaencadeada.Elemento@7229724f, exercicio3listaencadeada.Elemento@16b98e56, exercicio3listaencadeada.Elemento@7ef20235, exercicio3listaencadeada.Elemento@27d6c5e0, exercicio3listaencadeada.Elemento@4f3f5b24, exercicio3listaencadeada.Elemento@15aeb7ab, exercicio3listaencadeada.Elemento@7b23ec81

 Removendo o valor 4 na lista: 
exercicio3listaencadeada.Elemento@7229724f, exercicio3listaencadeada.Elemento@16b98e56, exercicio3listaencadeada.Elemento@7ef20235, exercicio3listaencadeada.Elemento@27d6c5e0, exercicio3listaencadeada.Elemento@4f3f5b24, exercicio3listaencadeada.Elemento@15aeb7ab, exercicio3listaencadeada.Elemento@7b23ec81

Instead of the values stored in the elements. Can anyone tell me what I’m doing wrong?

1 answer

3


This is because when printing an object, implicitly it is called the method toString() of the same. As in your case the class Elemento does not possess this method, so it uses which was inherited from Object, that prints it the way you saw it.

But in your case, as you want to print the value of the element, simply state this explicitly. Assuming the class Elemento owns its getter:

public class Elemento {
    private int valor;

    public int getValor() {
        return valor;
    }
}

Just do:

public void imprimeLista() {
    for (int i = 0; i < ListaEncadeada.size(); i++) {
        if (i < ListaEncadeada.size() - 1)
            System.out.print(ListaEncadeada.get(i).getValor() + ", ");
        else
            System.out.println(ListaEncadeada.get(i).getValor());
    }
}

Another detail is that your remove method has 2 problems. One is that you are comparing one Elemento with a int, and will never be equal. In fact what you want is to compare the value of the element, then it would be if (elemento.getValor() == pValor) { remove }.

The other problem is that it does not remove all occurrences from the value. For example, if I do:

MinhaListaEncadeada lista = new MinhaListaEncadeada();
lista.inserirElemento(4);
lista.inserirElemento(4);
lista.removeElemento(4);
lista.imprimeLista();

This will print (assuming the method imprimeLista has already been corrected):

4, 4
4

This problem is because you are removing elements from the list at the same time as you iterate on it. When removing the first 4, the size of the list becomes 1, and in the second iteration the i is worth 1 and it comes out of for. The correct way to remove all occurrences of the same value is by using a java.util.Iterator:

public void removeElemento(int pValor) {
    Iterator<Elemento> it = ListaEncadeada.iterator();
    while (it.hasNext()) {
        if (it.next().getValor() == pValor)
            it.remove();
    }
}

Or, from Java 8:

public void removeElemento(int pValor) {
    ListaEncadeada.removeIf(e -> e.getValor() == pValor);
}

But if the idea is to remove only the first occurrence of the element, an alternative would be to interrupt the loop after the first removal:

while (it.hasNext()) {
    if (it.next().getValor() == pValor) {
        it.remove();
        break;
    }
}

Another alternative to print correctly is to overwrite the method toString() in class Elemento:

public class Elemento {    
    @Override
    public String toString() {
        return Integer.toString(this.valor);
    }
}

Then you don’t need to change the method imprimeLista, because when printing the Elemento, its value will already be printed. Just be careful not to abuse the toString and put too much information on it (read more on "What is the function of the method toString()?").


I also recommend changing the variable name to listaEncadeada (with the first lowercase letter), to adhere to the Java code conventions.

  • 1

    Thank you =] getValor solved the same problem

Browser other questions tagged

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