Use Java’s world-class sorting algorithms on your custom objects

A lot of people don’t realize that the standard Java libraries are kept up-to-date with world-class sorting algorithms. For example, Java 7 released with an implementation of Timsort for Arrays.sort.

Class/Method Type of Collection Algorithm
Arrays.sort array timsort (objects) or dual-pivot quicksort (certain primitives)
Arrays.parallelSort array merge sort
Collections.sort List merge sort

If you’re not familiar with the Comparable or Comparator interfaces, now might be the time. As long as your object implements Comparable you can use the above sort methods from the standard library. There are often great uses for Comparator as well, especially when you want multiple ways to sort the same objects. For the rest of the post I’ll deal just with Comparable.

Continue reading “Use Java’s world-class sorting algorithms on your custom objects”

Misunderstandings of HashSet (hopefully) put to rest

I continue to see misunderstandings of what a set is. A set is a collection that stores a single set of values. You can have “1,2,3,4,5” but not “1,1,2,3” because in the latter, there are multiple “1”s. If you have any implementation of set (HashSet, TreeSet) and you try to add a value that is already in that set, you will end up with the same thing you had before (i.e. you have “1,2,3” in a set, you try to add 1, you still only have “1,2,3”).

Continue reading “Misunderstandings of HashSet (hopefully) put to rest”