Wednesday, March 23, 2011

Advantages of Iterator over forEach

1. Iterator is a design pattern and is a light-weight container.
2. Iterator doesnt need to know what the collection is (i.e. a List or sth else )
3. Using iterator ,we can remove the current element. The for-each loop hides the iterator, so you cannot call remove. Therefore, the for-each loop is not usable for filtering.
4. Similarly, forEach is not usable for loops where you need to replace elements in a list or array as you traverse it, but Iterator can be used.
5 .Finally, forEach is not usable for loops that must iterate over multiple collections in parallel.

Friday, March 4, 2011

finally Vs finilize


  • finally – The finally block always executes when the try block exits, except System.exit(0) call. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

  • finalize() – method helps in garbage collection. A method that is invoked before an object is discarded by the garbage collector, allowing it to clean up its state. Should not be used to release non-memory resources like file handles, sockets, database connections etc because Java has only a finite number of these resources and you do not know when the garbage collection is going to kick in to release these non-memory resources through the finalize() method.