If I have a rarely used collection in some class which may be instantiated many times, I may sometimes resort to the following \"idiom\" in order to save unnecessary object crea
The suggested answers are absolutely correct, just small tip - in Java 8 you can use the new Optional class to handle the case where the list instance is null, in a more functional approach.
For example, something like this:
public static List addElement(List list, String toAdd) {
List newList = Optional.ofNullable(list).orElse(new ArrayList<>());
newList.add(toAdd);
return newList;
}
Following a tip in the comments, it's better to replace new ArrayList<>()
with Collections.emptyList()
in order to prevent the creation of a new instance of an empty ArrayList
public static List addElement(List list, String toAdd) {
List newList = Optional.ofNullable(list).orElse(Collections.emptyList());
newList.add(toAdd);
return newList;
}