Print contents of an object belonging to a Treeset (Collection)

Asked

Viewed 62 times

0

I have a Treeset that will store several objects of a class "Products", this class has 3 attributes:

int commodity; String descProduct; float precoProduct;

After storing some "Product" objects in this Treeset, I need to print the contents of each of them. For this, I made this method:

public String imprimeLista(){
    Iterator<Produto> i = lProdutos.iterator();
    while (i.hasNext()){
        System.out.println(i.next() + " ");
    }
    return("");
}

I registered 2 products to test, and what it prints is:

proj.catalogo.Product@28d93b30

proj.catalogo.Product@1b6d3586

How can I make it to print codProduct, descProduct and precoProduct?

  • 3

    Also don’t use float for monetary value: https://answall.com/q/219211/101. You should use a for ( : ) instead of writing the loop at hand. The error is because you cannot print the object, you have to do a method to do this for yourself or create a printing algorithm for the individual members. Don’t use the toString() almost everyone uses but it was not made to print things, it is a method of debugging and returning a data simple and with easily recognizable identity and parseable.

1 answer

-1


You need to implement the method toString() of your class Produto. Take an example:

public class Produto {

    private int codProduto; 
    private String descProduto; 
    private float precoProduto;

    @Override
    public String toString() {
        return "Produto {" +
                "codProduto=" + codProduto +
                ", descProduto='" + descProduto + '\'' +
                ", precoProduto=" + precoProduto +
                '}';
    }
}

Output example:

Produto{codProduto=123, descProduto='Descrição', precoProduto=123.0}

This method toString() can be easily generated by your favorite IDE.

Bonus tip: instead of using Float to represent monetary values, consider using BigDecimal.

Browser other questions tagged

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