How do I display what's inside the list?

3

I have this method that adds things to the list:

 public Pedido adicionarPedido(int quantidade, String nome){

        lista.add(new Item(quantidade, nome ));
            return this;
 }

And instantiated in this class the attributes in the list:

List<Item> lista = new ArrayList<Item>();

I'm asking you to display in the toString method the list data plus the person's name:

     public Pedido ToString() {
        mensagem = "Pedido [lista=" + lista.get(0) +  lista.get(1) + ", cliente=" + cliente.getNome() + "]";
          return this;
     }

The problem is that the console is printing like this:

Pedido [lista=teste.Item@15db9742 teste.Item@6d06d69c, cliente=Aline Gonzaga]

But I want the items in the list to be printed.

How can I do this?

    
asked by anonymous 16.11.2016 / 14:02

2 answers

3

Your Item class needs to overwrite the toString method. By default the method shows a hashing single generated by JDK . Then it would look something like this:

@Override
public String toString() {
  return String.valueOf(this.getQuantidade()) + " " + this.getNome();
}

Whenever a method that receives a String as a parameter and an object is passed, the toString method is invoked. In case of a list, the method of your items is invoked, causing the effect you described (Item @ ...).

Soon after you can override the method of the requested class:

@Override
public String toString() {
  return "Pedido: lista=" + this.getLista() + ", cliente=" + this.getCliente().getNome();
}

So the following call:

System.out.println(pedido);

Will produce:

Pedido: lista=[1 Produto 1, 2 Produto 2], cliente=Aline Gonzaga

I also noticed that you used the ToString method with a capital letter. By the code convention Java the methods must start with a lowercase letter, with the exception of the constructors. Then you should override the toString method.

As for the usage and suggestion about abusive use of toString #, we have this topic in stackoverflow which indicates that the usage is interesting for debugging purposes, so perhaps to show a final message in your application is another method to define the message.

    
16.11.2016 / 14:07
4

For me it is an abuse to use ToString() for this, this method was not created for this kind of thing.

You should get the element and class member, and you should do this by sweeping the list, something like this:

 public Pedido ToString() {
     mensagem = "Pedido do Cliente " + cliente.getNome() + "\n";
     for (Item item : lista) {
         mensagem += "Quantidade: " + item.quantidade + " Produto: " + item.nomeProduto + "\n";
     }
     return this;
 }

I could only respond by looking at your previous question . All of this code still has several other problems.

    
16.11.2016 / 14:21