How to have an ArrayList by composition

1

I understand how to do composition but I have never done with lists, although the principle should be the same, I do not understand how to do it.

To start I have a class CentroComercial that has a ArrayList called lojas which will pass by attribute in construtor .

Lojas is a ArrayList that stores objects of type Loja . being this super-class divided into several subclasses. And I have two doubts.

  • How do I do the

    public void setLojas(ArrayList<Loja> lojas) {}
    
  • What is the best way to instantiate Arraylist?

  • private ArrayList<Loja> lojas;

    private ArrayList<Loja> lojas = new ArrayList<Loja>();

    or some other way?

        
    asked by anonymous 15.04.2018 / 16:47

    1 answer

    2

    If the method you are going to have is

    public void setLojas(ArrayList<Loja> lojas) {}
    

    Then just declare the ArrayList as

    private ArrayList<Loja> lojas;
    

    However, if you want to ensure that you have a valid loja object in order to avoid possible NullPointerException use:

    private ArrayList<Loja> lojas = new ArrayList<Loja>();
    

    This is the preferred way as it allows you to safely identify / indicate when the Shopping Center has no associated stores (you can use lojas.size() ).

    The setLojas() method will be like this

    public void setLojas(ArrayList<Loja> lojas){
        this.lojas = lojas;
    }
    

    If you do not want to externally change the saved ArrayList, create a new instance.

    public void setLojas(ArrayList<Loja> lojas){
        lojas = new ArrayList<Loja>(lojas);
    }
    

    If you have a get method this should also return a new instance

    public ArrayList<Loja> getLojas(){
        return new ArrayList<Loja>(lojas);
    }
    

    The object loja should also be immutable.

        
    15.04.2018 / 17:29