Friday, August 19, 2011

Ordered Map vs Sorted Map

This is obvious once you know it (isnt’ everything).

A little bit of a rant at declining standards first.. (its ok, I’m not lamenting the youth of today, or society; its my own declining standards I’m ranting about)..

I feel that a lot of times I rely on google to give me a quick solution to a problem. There’s nothing inherently wrong with this. I imagine 95% of developers do it and certainly it leads to quicker solutions. One negative consequence of this is that I don’t get any depth of knowledge, just a quick link to a possible solution which I often can paste in to fulfil my needs. Little effort, quick result, but little return and learnt. In some ways this blog is an attempt to expand some of these topics just a little bit more, in order to get a better understanding of them, but it too has a bit of the copy and paste solution about it.

Of course this only works if you 1/ Ask the correct question, and 2/ form your question correctly.... So today (possibly as a result of years of quick solution hunting, and no learning) I forgot some of the basics, and didn’t ask the correct question.

I had a Map instance where I wanted to control the sequencing of the keys. I knew this class existed in the java.util Collections classes (or failing that the commons collections), so I was frantically searching the web for a Sorted Map.

I found java.util.SortedMap. Perfect ...
I read the javadoc description and thought.. this isn’t what I want... It sorts on natural Order, or based on applying a custome comparator. After much head scratching about how I would create a custom comparator to order my Map in the order which it was created, I finally had my Eureka moment... I didn’t want a Sorted Map at all

Of course what I really wanted was java.util.LinikedHashMap. This stores the Keys within an internal LinkedList structure that maintains the order of the elements as they are added. Quite different to a sorted List which dynamically sorts the keys based on a algorithm (either natural or custom).

So todays lesson is simple. Learn the basic terminology before consulting the almighty google. And LinkedHashMap is quite different to SortedMap

Sunday, August 14, 2011

Gson inheritance

This article helped fix a problem I had with inheritance, and Gson (JSON api)

Basically, key is to ensure that you specify the field values as private fields, and assign their values in the constructor (not by creating a new private field with an updated value)

Monday, August 01, 2011

jconsole for high level profiling

I’ve mentioned it obliquely before but its time I highlighted the free profiling tool jconsole.

Always good to infrequently check your application especially if you are getting OutOfMemory errors.

It also doubles up as an MBean browser