We had a test that failed randomly with different actual results today. After spending half an hour on it, I finally figured out what was going on. My coworkers had sorted a list of products first and then used them as keys to create a HashMap. Later on they got the key set out of the HashMap and hope to process the products in order. What they forgot is that Set is not sorted therefore won’t return stuff in the same order they are put in. Our progressive rounding calculator happens to be very order dependent.
You should only sort a collection right before you need it to be sorted. This way you won’t miss a sort. It also makes the interface clearer because sorting a collection should be part of your implementation and other people who are using your API shouldn’t have to do the sort for you.