Accessing List of another class

Asked

Viewed 103 times

-3

I have a Warehousing class that contains a list of products, as would the interaction of this list in the managed class using the returned methodProduct() without parameters. On the output of my code is giving null.

Armazen class

public class Armazem {
  List<Produto> produtos;

  Armazen(){
        this.produto = new ArrayList<Produto>();    
  }
  public void adicionarProduto(Produto p) {
            produtos.add(p);    
  }
  public List<Produto> getProdutos() {
        return produtos;
  }

Classe Gerencia

public class Gerencia{
    Armazen a = new Armazen();
    private String N_estoque;
   
    public Gerencia(String N_estoque) {
       this.N_estoque = N_estoque;  
   }
   public  Gerencia retornaProdutos() { 
       for(Armazen pdto : a.getProdutos()) 
              System.out.println("esses são os produtos"+ pdto);
    
}


  public static void main(String[] args) {
       Produto arroz = new Produto("Arroz");
       Gerencia gerencia = arroz.retornaProdutos();
      System.out.println("Em estoque: " + gerencia);

}

  • If anyone can help me out on this.

  • My great difficulty is in understanding how to use a list that was populated in another class, I have tried to create a reference to type class( List<otherClasse> otherClasse; ), and I could not, I have already looked for some examples but I still could not understand.

  • Hello friend, thanks for your attention, It was just typo even because I did on the mobile this post, even with this.products is returning null.

1 answer

1


In the class builder Armazen, you are using this.produto and not this.produtos, because the variable declared in that class is produtos, and not produto.

In his method of retornaProdutos in class Gerencia you should return void or make a return according to what you want. And within the parameters of for, you should do Produto pdto : a.getProdutos(), for each returned element of a.getProdutos() is a Produto, and not a Armazen.

And in case this logic of yours to save the return of retornaProdutos within a variable and then returns it within a String will not work as you are not returning a list.

Also, in the main method you are not adding any product in the list.

Suppose you did import ArrayList and List correctly, and the class Produto exist, I believe your code will work correctly with these changes.

  • Thank you friend I will make the changes you have indicated to me.

Browser other questions tagged

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