Thursday, September 17, 2009

Differences between HashMap and HashTable

Both provide key-value access to data. The Hashtable is one of the original collection classes in Java. HashMap is part of the new Collections Framework, added with Java 2, v1.2.

The key difference between the two is that access to the Hashtable is synchronized on the table while access to the HashMap isn't. You can add it, but it isn't there by default.

Another difference is that iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn't. If you change the map while iterating, you'll know.

And, a third difference is that HashMap permits null values in it, while Hashtable doesn't.

For new code, use HashMap as much as possible.

If you want Keys in HashMap to be Case - Insensitive, follow this technique:
http://www.velocityreviews.com/forums/t140140-case-insensitive-keys-using-collections.html
* Store keys in LowerCase while popluating the map.
* Always use .LowerCase() on lookupKey before doing a get()

Complexity of Lookup on HashMap is not alway O(1). It depends on HashMap size. If multiple keys in HashMap match a lookupKey, then it traverses linear O(n) on matched Keys.

4 Ways to traverse HashMap - Link

Tuesday, September 15, 2009

All about try-catch-finally

try {
statements;
} catch (exceptionType1 identifier1) { // one or multiple
statements;
} catch (exceptionType2 identifier2) {
statements;
}
...
} finally { // one or none
statements;
}

* must include either one catch clause or a finally clause
* can be multiple catch clauses but only one finally clause
* the try statements are executed until an exception is thrown or it completes successfully

* a compile-error occurs if the code included in the try statement will never throw one of the caught checked exceptions (runtime exceptions never need to be caught)
* if an exception is thrown, each catch clause is inspected in turn for a type to which the exception can be assigned; be sure to order them from most specific to least specific
* when a match is found, the exception object is assigned to the identifier and the catch statements are executed
* if no matching catch clause is found, the exception percolates up to any outer try block that may handle it
* a catch clause may throw another exception

* if a finally clause is included, it's statements are executed after all other try-catch processing is complete
* the finally clause executes wether or not an exception is thrown or a break or continue are encountered

Note
====
* If a catch clause invokes System.exit() the finally clause WILL NOT execute.