The general sorting program
In the previous chapter, we implemented a simple sort algorithm. The code can sort elements of a String
array. We did this to learn. For practical use, there is a ready cooked sort solution in the JDK that can sort members of collections
, which are comparable.
The JDK contains a utility class called Collections
. This class contains a static Collections.sort
method that is capable of sorting any List
that has members that are Comparable
. List
and Comparable
are interfaces defined in the JDK. Thus, if we want to sort a list of Strings, the simplest solution is as follows:
public class SimplestStringListSortTest { @Test public void canSortStrings() { ArrayList actualNames = new ArrayList(Arrays.asList( "Johnson", "Wilson", "Wilkinson", "Abraham", "Dagobert" )); Collections.sort(actualNames); Assert.assertEquals(new ArrayList<String>(Arrays.<String>asList( "Abraham...