I believe that’s what you want:
class Produto{
private Integer codigo;
private String descricao;
private Integer quantidade;
public Produto(Integer codigo, String descricao, Integer quantidade){
this.codigo = codigo;
this.descricao = descricao;
this.quantidade = quantidade;
}
/*Getters setters*/
@Override
public String toString(){
return this.codigo+" "+this.descricao+" "+this.quantidade;
}
}
Now that you have your class Produto
, you can create some objects of it and add to a ArrayList
of Produto
Produto produtoCueca = new Produto(1, "Cueca", 5);
Produto produtoCalcinha = new Produto(2, "Calcinha", 5);
//Lista de produtos
ArrayList<Produto> listaProdutos = new ArrayList<Produto>();
listaProdutos.add(produtoCueca);
listaProdutos.add(produtoCalcinha);
Explanation of toString
:
In java, when you try to print an instance of a class, it calls the method toString
of that class. But as you did not make the definition of this method, the toString
is called from the parent class, in case Object
, which causes the System.out.println
do not stay in the way desired.
So if you want to customize how an instance of your class will be printed, you have to override the method toString
.
Reference:
when to use toString() method
You want to know how to read an arraylist of custom objects using correct stream?
– user28595
@Diegof I need to understand how to create a generic type, in my example I use the
ArrayList<String>
would like to useArrayList<Produto>
.– Gabriel Rodrigues
Wouldn’t be the case to use Generics Type? http://www.tutorialspoint.com/java/java_generics.htm
– NilsonUehara
@Nilsonuehara this would be like c template++?
– Gabriel Rodrigues
I don’t know C++. I’ll post an answer with an example of use.
– NilsonUehara
I posted an answer, but I would really like to understand your problem in order to improve it. Your question is on how to create a class
Produto
and an instance of it? Or are you using Java Generics?– Rubico