Question about getting and settings and when to use superclasses

I have the following get method:

public List<PersonalMessage> getMessagesList() {
    List<PersonalMessage> newList = new ArrayList<PersonalMessage>();

    for(PersonalMessage pMessage : this.listMessages) {
        newList.add(pMessage.clone());
    }

    return newList;
}

And you can see that if I need to change the implementation from ArrayListto something else, I can easily do it, and I just need to change the initialization newListand all the other code, which depends on the fact that getMessageList()return will still work.

Then I have this set method:

public void setMessagesList(ArrayList<PersonalMessage> listMessages) {
    this.listMessages = listMessages;
}

My question is: should I use Listinstead of `ArrayList in the method signature?

I decided to use it ArrayList, because this way I can force the implementation I want, otherwise there may be a mess with different types of lists here and there.

But I'm not sure if this is the way ...

+3
3

setter . ?

public void setMessagesList(Collection<PersonalMessage> messages) {
    this.listMessages = new ArrayList<PersonalMessage>(messages);
}
+7

, (List). , , - , ArrayList .

, List. .

, getter/setter, .

+2

PersonalMessages ? ? Paramater Iterable .

0

Source: https://habr.com/ru/post/1746710/


All Articles