How to have an Arraylist by composition

Asked

Viewed 122 times

1

I understand how to compose but I’ve never done with lists, although the principle should be the same, I don’t understand how to do.

For starters I have a class CentroComercial who owns a ArrayList calling for lojas which will pass as attribute in construtor.

Lojasis a ArrayList which stores objects of the type Loja. this super-class is divided into several subclasses. And I have two doubts.

  1. How should I do the

    public void setLojas(ArrayList<Loja> lojas) {}
    
  2. what is the best way to instill the Arraylist?

private ArrayList<Loja> lojas;

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

or otherwise until?

1 answer

2


If that’s the method you’re gonna have

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

Then it will be enough to declare the Arraylist so

private ArrayList<Loja> lojas;

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

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

This is the preferred way since it allows identifying/indicating safely when Centrocomercial does not have associated stores (you can use lojas.size()).

The method setLojas() it will be so

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

If you do not want it to be possible to change the stored Arraylist externally, create a new instance.

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

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

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

The object loja should also be immutable.

  • but this ensures that stores are by composition? I modifying lojas, do not change the list of lojas at any instance of CentroComercial who has this list?

  • You need to explain better what you want. So that it is not possible to modify Arraylist lojas it will have to be passed to the builder and the method setLojas() cannot exist. If so say that I add to the answer.

  • The Arraylist can and must be in the constructor, is an attribute of CentroComercial but must be implemented by composition. so that if I modify the list in any way in another class, any instance of CentroComercial did not change his list. this is the code I have and I’m having doubts. https://snag.gy/ifSbpP.jpg

  • Now I understand. I think its implementation is correct since it keeps a new instance and also returns a new instance. You just have to make sure that an object loja is also immutable.

  • That constructor that accepts a Centrocomercial would perhaps be preferable to replace it with an implementation of the method clone()

Browser other questions tagged

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