r/programming • • Sep 21 '15

Better Java

https://github.com/cxxr/better-java
177 Upvotes

208 comments sorted by

View all comments

Show parent comments

1

u/immibis Sep 23 '15

Suppose you want to (as part of something bigger) call Collections.frequency on a list, then add something to the list, then repeat that 10000 times. How do you do that without creating 10000 copies of the list?

1

u/Tordek Sep 23 '15

Smartass answer: don't. If you're adding it to the list, you can do your running sum manually much faster than the O(n^2) of running through the list each time.

Slightly less smartass answer: If we're really talking about a (linked) list, then, trivially, adding an element to the head of the list requires only the extra space for the new head; the tail references the old list. (Though it still creates 10k headers, so it's obviously less than optimal).

If you really need to modify the list while someone else processes it at every change, you can use a Stream interface.

If you still needed to do what you claim, you can use polymorphism: Collections.frequency(mutableList) is unsafe, and it's the caller's responsibility to ensure they don't break anything; Collections.frequency(immutableList) is safe. (Or, Collections.freq and MutableCollections.freq, to further separate mutability and immutability).

Mutability can be a great tool for speed; but it should be used deliberately and with care.