ONJava.com -- The Independent Source for Enterprise Java
oreilly.comSafari Books Online.Conferences.


AddThis Social Bookmark Button

Using the Jakarta Commons, Part 1
Pages: 1, 2, 3

3. Lang

Summary: An extension of the java.lang package with many useful additions for String manipulations. Provides C-like enumerations as well.

Where: Main Page, Binaries, Source.

When: When you are unhappy with the default methods provided in the java.lang package and want to take more control over String manipulation, numeric methods, and System properties. Also, when you want to use C-like enumerations.

Example Applications: LangDemo.java, Mortgage.java, OnTV.java. Requires commons-lang.jar in the CLASSPATH.


A number of utility methods in this package are provided that make the life of the Java programmer easier. These methods, mostly static, reduce the coding required for everyday functions. This is most visible in the StringUtils class, which allows you to manipulate strings over and above the methods provided by the standard java.lang.String package. Using them is as simple as calling a static method with the right parameters. For example, to capitalize a string, you would simply use:


The output of this method, as expected, would be Name. Browse the rest of the StringUtils API for the rest of the static methods, and you will probably see something that you could use in your code. The example application exercises some of the methods.

Another interesting class is the RandomStringUtils class. This class provides methods to create random Strings, which can be really useful in creating random passwords.

The NumberUtils class provides methods for number manipulations. Interesting methods exist in this class, such as finding the maximum or minimum, and converting Strings to numbers. The NumberRange and CharRange classes provide a way of creating and manipulating ranges of numbers and characters, respectively.

The classes in the Builder package provide methods to build toString, hashCode, compareTo, and equals methods for classes. The idea is to build quality toString, equals, compareTo, and hashcode methods for your classes where you don't need to specify these methods yourself. You can simply use the methods in the Builder packages to build these methods. For example, using the ToStringBuilder method, you can create a toString representation for your class as follows:

public class Mortgage {
	private float rate;
	private int years;

	public String toString() {
		return new ToStringBuilder(this) .
			append("rate",  this.rate)   . 
			append("years", this.years)  .

Why would you use a method like this? It allows for a consistent way of handling all data types, returns null properly, and enables you to control the level of detail for objects and collections. This is applicable for all of the builder methods, and the syntax is similar to the one shown above.

For developers who miss C-style enums in Java, this package fills the void by providing a type-safe Enum data type. The Enum class is abstract, so to create your own enumerations, you need to extend this class. This is best illustrated with an example:

  1. Define, and extend your enumeration class:

    import org.apache.commons.lang.enum.Enum;
    import java.util.Map;
    import java.util.List;
    import java.util.Iterator;
    public final class OnTV extends Enum {
    	public static final OnTV IDOL     = new OnTV("Idol");
    	public static final OnTV SURVIVOR = new OnTV("Survivor");
    	public static final OnTV SEINFELD = new OnTV("Seinfeld");
    	private OnTV(String show) {
    	public static OnTV getEnum(String show){
    		return (OnTV) getEnum(OnTV.class, show);
    	public static Map getEnumMap() {
    		return getEnumMap(OnTV.class);
    	public static List getEnumList() {
    		return getEnumList(OnTV.class);
    	public static Iterator iterator() {
    		return iterator(OnTV.class);
  2. Now simply use this in your own methods as you would use an enumeration:


This returns the Idol item from the enumeration data type that we have created. The Enum class provides other useful methods for fully using this class.

4. Collections

Summary: An extension of the Java Collection Framework with great new data structures, iterators, and comparators.

Where: Main Page, Binaries, Source.

When: I recommend the use of the Collections API in almost all serious Java development projects where you need to work with data structures. The value that this API brings in over the regular Java implementations is tremendous.

Example Application: CollectionsDemo.java. Requires commons-collections.jar in the CLASSPATH.


There are too many classes in the Collections API to do justice to them in a single section. However, I will cover the most important ones here and hope that I have piqued your interest enough to take a serious look at the remaining ones. The API documentation itself provides a lot of information on how to use each of the classes.

The Bag interface extends the regular Java Collection by allowing a count to be kept of all elements in the Bag. A Bag is useful in situations where you want to track the number of elements going into or out of your collection of elements. Since Bag itself is an interface, you must use any of the implementing classes, such as HashBag or TreeBag. As the names suggest, HashBag implements a HashMap based Bag, while a TreeBag implements a TreeMap based Bag. Two important methods on the Bag interface are getCount(Object o), which returns the count of a particular element in the Bag, and uniqueSet(), which returns the unique elements in the Bag.

The Buffer interface allows you to remove objects from your collection based on a predefined order. This order can be LIFO (Last In First Out), FIFO (First In First Out), or you can define your own ordering. Let us see how we would implement a Buffer where the removal of elements is based on the natural sort order.

  1. The BinaryHeap class that implements the Buffer interface provides for removing elements based on the natural sort order. To reverse this sort order, pass a value of false, which indicates to the Heap that you want a reverse of the natural sorting.

    BinaryHeap heap = new BinaryHeap();
  2. Add your elements to this heap:

     heap.add(new Integer(-1));
    heap.add(new Integer(-10));
    heap.add(new Integer(0));
    heap.add(new Integer(-3));
    heap.add(new Integer(5));
  3. Call remove on this heap. Based on the natural sort order, -10 will be removed from this collection of elements. If we had requested reverse sort order, 5 would have been removed.


The FastArrayList, FastHashMap, and FastTreeMap classes operate in two modes over the corresponding regular Collection classes. The first mode is the "slow" mode, and is ideal for when these classes are being constructed and initialized. During "slow" mode, changes in the structure (addition or deletion of elements) of these classes is synchronized. In the "fast" mode, the access to these classes is thought to be read-only, and therefore is faster, as no synchronization takes place. Structural changes, if required during the fast mode, are accomplished by cloning the existing class, making modifications on the cloned class, and finally, replacing the existing class with the cloned one. These classes are useful in multithreaded environments where most access, after initialization, is read-only.

The iterator package provides iterators for various collections and objects that are not present in the regular Java Collections package. The example application exercises the ArrayIterator, which iterates over the contents of an Array. Using these iterators is the same as using the normal Java iterators.

Finally, some useful comparators are provided in the comparator package. A comparator is a class that allows you to define a way of comparing and deciding the sort order of two objects of the same class. For example, in the Buffer class that we talked about earlier, we could have defined our own comparator, and used it to impose a sorting order instead of going with the natural sorting of elements. Let us see how we would actually do this:

  1. Create a new BinaryHeap class, but this time, use a NullComparator. A NullComparator compares nulls against other objects to decide whether or not a null is higher than other objects based on the value of the flag nullsAreHigh. If this value is set to false, nulls are deemed to be lower than other objects.

    BinaryHeap heap2 = new BinaryHeap(new NullComparator(false));
  2. Add objects to this heap along with some nulls.

    heap2.add(new Integer("6"));
    heap2.add(new Integer("-6"));
  3. Finally, remove an element. The resulting Bag contains one fewer null, as nulls are lower than all other objects.


This concludes our discussion of the Trivial category. For further details, read the API documentation, or better still, look at the source code of these packages.

Pages: 1, 2, 3

Next Pagearrow