Collections with wrong elements
The bug is not trivial, and as usual, this is not in the implementation of the algorithm, but rather in the definition, or the lack of it. What should the program do if there are not only strings in the collection that we sort?
If I create a new test that starts with the following lines, it will throw ClassCastException
:
@Test public void canNotSortMixedElements() { ArrayList actualNames = new ArrayList(Arrays.asList( 42, "Wilson", "Wilkinson", "Abraham", "Dagobert" )); ... the rest of the code is the same as the previous test
The problem here is that Java collections can contain any type of elements. You cannot ever be sure that a collection, such as ArrayList
, contains only the types that you expect. Even if you use generics (we have not learned that, but we will in this chapter), the chances of a bug somehow conjuring up some object of an inappropriate type into a collection, are smaller but are still there. Don't ask...