
add ( 3 ) // modifies `list` resizes and inserts new entry list += 3 // đ¤ˇââď¸ it depends on the declared type of the list Lessons List + 3 // you've ignored the new list here be dragons â ď¸đ list. plus() methods would perform on a large-ish list of Integers. Crude performance testÄŻor consideration, I was curious how both the. plus() in most, if not all, cases itâs cheaper to expand an ArrayList than it is to copy the whole list and add a new entry to it. There are times when ensuring your original list is not mutated is beneficial, and conversely there are times when performance concerns might mean you donât want to create a new copy of the list each time you add to it. For other collections, like ArrayList, youâll be able to choose either approach. For some collection types, there wonât even be an option. Thereâs probably not a single answer here which is best will depend on your use case.

Whereas if you explicitly have a MutableList then += can do the more performant adding of the item without creating a whole new list. This is because a List type doesnât indicate it is mutable. When the declared type is a List, then calling += will result in creating a brand new list and copying the old one into it. Why? As above, the type youâve declared the list as (rather than the implementation itself) is the determining factor in what += will actually do when you use it.

To fix this, we need to stop ignoring the returned list. We call foo + 2 and are given another new list back, which we ignore again.

When we call foo + 1 we are given a new list back that we ignore. So this now explains why, in our original example, we were left looking at an empty list.

Hereâs the important thing to remember: it doesnât modify the original list. adds all elements from the original list to it.Note the signature of this function: it has operator in the signature and is called plus - this is why it is invoked when you call foo + 1. * Returns a list containing all elements of the original collection and then the given.
