Developmentality

The blog of Nicholas Dunn, an aspiring software developer living in Virginia

Note: This blog has moved to http://developmentality.wordpress.com
Wed Dec 2

Apache Commons Primitive Collections

Do you ever work with libraries that require you to pass around primitive arrays?  If you do, you’ve probably run into the pain involved with trying to create these arrays if the underlying data is variably sized.  Why is it painful in Java?  Because the wonderful Collection classes that exist are for Objects only, and not primitive types.  There are no variable sized collections for primitive types.  So you might find yourself doing the following:



// need a double[] matching some criteria for a library call

List doublesMatching = new ArrayList();

// populate the list 

double[] array = new double[doublesMatching.size()];

for (int i = 0; i < array.length; i++) {

  array[i] = doublesMatching.get(i);

}

// Use the array

libraryFunction(array);

Apache Commons has a whole slew of variable sized primitive collections, making your intent much clearer, and your code shorter.  Furthermore, if you have to deal with a huge amount of these primitive types, you gain a substantial space boost by not having the autoboxed object bloat.

Here is that same code above, avoiding all of the autoboxing and copying:



DoubleCollection doubles = new ArrayDoubleList();

// Populate doubles list; autoboxing is avoided

libraryFunction(doubles.toArray());

Comments (View)
blog comments powered by Disqus