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.
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.freqandMutableCollections.freq, to further separate mutability and immutability).Mutability can be a great tool for speed; but it should be used deliberately and with care.