Collection operations



max      min

binarySearch
copy
fill
indexOfSubList
lastIndexOfSubList
list
     replaceAll
reverse
rotate
shuffle
sort
swap

disjoint      frequency
Java 5 adds only two more, disjoint and frequency. disjoint returns true if two collections have no elements in common. frequency counts the number of occurances of an object in a collection.

I'd submit that neither of these is particularly common. (Turning to Google codesearch again gives about a dozen occurances of the two put together). Further, I'd suggest this is another example of the Java libraries lazy development. Neither of these methods have an overload that takes a Comparator, for example.

I mentioned that one of these methods doesn't operate a List. Anyone know what the odd one is? It's called list. It was added in Java 1.4. It takes an Enumerator and uses it to fill an ArrayList. It's apparently to provide interop between legacy APIs that return enumerations and new APIs that need collections. 5 uses according to Google codesearch, none of which actually do this. Most just convert the ArrayList to an array. One takes the list, sorts it, then iterates over it, using the values to look up into a Map. Duh. My initial suspicion was that this list methods was used in Java itself, and someone though "ooh, that's useful". But I was wrong. It isn't. Curiously though, although this is backward looking "oh, those horrible enumerations", it might point to the future.

By way of comparison, .NET provides even fewer collection operations and they are provided as static methods on particular classes. System.Collections.ArrayList has sort, reverse and binary search, but that's about it. By way of further contrast, the C++ Standard Library provides around 60 things you can do with collections.

We accept that collections - sequences of some kind - are pretty fundamental to what we do as programmers. Consequently, I think we should expect our libraries to give us lots of things to do with them. Java doesn't, nor does it give a good model for what such a library might look like, so we spend a lot of time writing crappy for loops. We do it without even realising. Why? Because we don't think about it, because we don't have the language to express it.

Are these really a very useful list of operations? There's not even a basic linear search. If you were going to add to them, what would you add, and what would it look like?

Let's write the search.