Wednesday, June 23, 2010

Creating a Collection with a single element

Question: What is the most efficient way of creating a collection (Set, List or Map) with a single element?

Answer: The most efficient way of creating a collection with a single element would be to make use of the Collections.singletonXXX() methods.
  • Collections.singleton - To create a set that has only one element.
  • Collections.singletonList - To create a list that has only one element.
  • Collections.singletonMap - To crate a map that has only one entry.
The collections returned from these methods are immutable.

Compare these methods with Collections.unmodifiableXXX() methods. The umodifiableXXX methods already accept a collection as an argument.

Sunday, June 20, 2010

Java Native Access - An essential tool in Java tool box

I recently learned about Java Native Access (JNA) and was simply amazed at how easy it is to make native calls. I have used JNI earlier in my projects to access native code, but it is a bit painful experience. JNA makes it a bit easier to make those native calls. I haven't experimented much with passing structures and getting structures (or pointers to structures) as return values. As far as the arguments and return types are one of the primitive types, the interface is very easy to define and use.

Give it a try, you will like it.