Problems with a Linked List object in Java

1

I'm learning from the Caelum workbooks data structures, and I started to see Liagada Lists, I followed all the code that it offers, step by step and I understood the logic of the list chained, but what I did not understand was this line of code:

System.out.println(lista); // lista é um objeto to tipo ListaLigada

That has output the array of strings:

  

[Paulo, Rafael]

I do not understand, because in my code the output that it gives is only the name of the class + the hascode of the object. Someone explain to me what happened ??? All the code to avoid bureaucracy is there:

public class Celula {

  private Celula proxima;

  private Object elemento;

  public Celula(Celula proxima, Object elemento) {
    this.proxima = proxima;
    this.elemento = elemento;
  }

  public Celula(Object elemento) {
    this.elemento = elemento;
  }

  public void setProxima(Celula proxima) {
    this.proxima = proxima;
  }

  public Celula getProxima() {
    return proxima;
  }

  public Object getElemento() {
    return elemento;
  }
}

The LinkedList class:

public class ListaLigada {

  private Celula primeira;

  private Celula ultima;

  public void adiciona(Object elemento) {}
  public void adiciona(int posicao, Object elemento) {}
  public Object pega(int posicao) {return null;}
  public void remove(int posicao){}
  public int tamanho() {return 0;}
  public boolean contem(Object o) {return false;}
}

The test code:

    public class TesteAdicionaNoFim {
      public static void main(String[] args) {
        ListaLigada lista = new ListaLigada();
        lista.adiciona("Rafael");
        lista.adiciona("Paulo");

        System.out.println(lista);
       }
     }

NOTE: I DO THE SAME CODE, EQUAL. EVERY LINE EXACTLY THE SAME WITH CAELUM'S APOSTILA

    
asked by anonymous 24.10.2016 / 05:30

2 answers

1

To print a list in Java, you have to go through it. Here is an example:

for (String nome : lista){
    System.out.println(nome);
}

The issue of printing the list will be solved. But as the friend said above, you have to review the contents of this book.

    
24.10.2016 / 16:10
1

I can not guarantee that the code was actually typed exactly. If it was and the intention was to do what is in the question then the handout is wrong, which does not surprise me where it came from.

When you print the object it is something like this ListaLigada@52e922 same as it will receive.

To list the elements you need to create a method that lists them. Did not they leave it as an exercise for you?

Some people like to overwrite ToString() to do this, I think it's abuse.

Note that even though this problem is solved, the adiciona() method does nothing, so it does not resolve. This class is incomplete.

The correct solution would be to create an iterator (through the Iterable , but this is too complex for anyone who is starting and I doubt that a booklet is meant to teach anything beyond the basics.

    
24.10.2016 / 05:58