Reputation: 97
Guys I have created an ArrayList and I don't want to make it immutable. I just seek to find a solution as for how to not allow the ArrayList from removing the objects.
public final class EMailArchive {
private final String name;
private final ArrayList <EMail> emailList;
private final LocalDate date;
public EMailArchive(String name, ArrayList <EMail> emailList) {
this.name = name;
this.emailList = emailList;
date = LocalDate.now();
}
public String getName() {
return name;
}
public LocalDate getDate( ) {
return date;
}
public List <EMail> getEMailList() {
return emailList;
}
public void addEMailToArchive(final EMail mail) {
emailList.add(mail);
// the mail added to the list shall not be removed, but how do i do that
}
}
Upvotes: 1
Views: 158
Reputation: 2981
If the solution above with extending ArrayList
is not appropriate for whatever reason, you could return a copy within the getter, like this:
public List <EMail> getEMailList() {
return new ArrayList<>(emailList);
}
Changes to the returned List
will not be reflected back to the class member.
Upvotes: 0
Reputation: 2208
One way is to implement a subClass of ArrayList that override the remove method
class myArrayLit extends ArrayList {
public myArrayList() {
super();
}
@Override
public remove(int index) {}
}
This is a basic example, there are more method to override, to achieve your goal.
Upvotes: 1