Rule of thumb for choosing an implementation of a Java Collection?

Tags: , ,



Anyone have a good rule of thumb for choosing between different implementations of Java Collection interfaces like List, Map, or Set?

For example, generally why or in what cases would I prefer to use a Vector or an ArrayList, a Hashtable or a HashMap?

Answer

I’ve always made those decisions on a case by case basis, depending on the use case, such as:

  • Do I need the ordering to remain?
  • Will I have null key/values? Dups?
  • Will it be accessed by multiple threads
  • Do I need a key/value pair
  • Will I need random access?

And then I break out my handy 5th edition Java in a Nutshell and compare the ~20 or so options. It has nice little tables in Chapter five to help one figure out what is appropriate.

Ok, maybe if I know off the cuff that a simple ArrayList or HashSet will do the trick I won’t look it all up. 😉 but if there is anything remotely complex about my indended use, you bet I’m in the book. BTW, I though Vector is supposed to be ‘old hat’–I’ve not used on in years.



Source: stackoverflow