Sorting: Collections.sort


You can sort a list of String objects quite simply, as this language test demonstrates:

 public void testSortStringsInPlace() {    ArrayList<String> list = new ArrayList<String>();    list.add("Heller");    list.add("Kafka");    list.add("Camus");    list.add("Boyle");    java.util.Collections.sort(list);    assertEquals("Boyle", list.get(0));    assertEquals("Camus", list.get(1));    assertEquals("Heller", list.get(2));    assertEquals("Kafka", list.get(3)); } 

The static sort method in the java.util.Collections class takes a list as a parameter and sorts the list in place.[1] If you do not want to sort the list in placeif you do not want to modify the original listyou can create a new list and send that list as a parameter to the sort message.

[1] The sort method uses a merge sort algorithm that splits the list of elements into two groups, recursively sorts each group, and merges all sorted subgroups into a complete list.

 public void testSortStringsInNewList() {    ArrayList<String> list = new ArrayList<String>();    list.add("Heller");    list.add("Kafka");    list.add("Camus");    list.add("Boyle");    ArrayList<String> sortedList = new ArrayList<String>(list);    java.util.Collections.sort(sortedList);    assertEquals("Boyle", sortedList.get(0));    assertEquals("Camus", sortedList.get(1));    assertEquals("Heller", sortedList.get(2));    assertEquals("Kafka", sortedList.get(3));    assertEquals("Heller", list.get(0));    assertEquals("Kafka", list.get(1));    assertEquals("Camus", list.get(2));    assertEquals("Boyle", list.get(3)); } 

The last four assertions verify that the original list remains unmodified.



Agile Java. Crafting Code with Test-Driven Development
Agile Javaв„ў: Crafting Code with Test-Driven Development
ISBN: 0131482394
EAN: 2147483647
Year: 2003
Pages: 391
Authors: Jeff Langr

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net