Wednesday, August 4, 2010

ArrayList vs Vectors

Many people coming from Java 1.4 era seem to have a liking for Vectors. Before the Collections framework brought with it loads of classes, Vectors were a good option to fall back on when you wanted a growable array of objects. Vectors did the job well, but then, there are differences how Vectors and ArrayLists work. So, don't just jump and adopt Vectors if what you need is just an ArrayList. I am listing down a comparison between the two.

  • Vectors are synchronized while ArrayLists are not. So, if you need to work within a multi-threaded environment, then choose Vectors. But, if you don't even know what multi-threading is, or you do not want the access to be synchronized, use ArrayList. ArrayLists will give you a performance improvement over Vectors in a non-multi-threaded environment.
  • When Vectors grow, they do so by a factor of 2, while ArrayList grow by a factor of 1.5. In most of the cases, this fact doesn't matter. But, if you are writing alogrithms and performance intensive code, you should consider this difference.
  • The growth factor can be adjusted for a Vector, if you really need to change that. But for ArrayLists, this cannot be changed.
  • Both ArrayLists and Vectors have excellent performance when it comes to retrieving elements by index. Updating through indexes are also fast.

Tuesday, May 26, 2009

Java Program: Fibonacci Example

The first two Fibonacci numbers are 0 and 1, and each remaining number is the sum of the previous two.

Here is the source code for generating the Fibonacci Series by using Recursion.

public class Fibonacci {
    //Number of Fibonacci numbers to be shown
    static int limit= 10;
    static int count = 0;
    public static void main(String[] args) {       
        System.out.print(0+” “);
    //Recursive Function
    private static void fibo(int i, int j) {
        System.out.print(j+" ");

This piece of code is ready to run. Copy this code into a file called, compile it and run. Here is the sample output of the above program. To generate the required number of numbers in the sequence, adjust the value of the integer variable “limit”.

0 1 1 2 3 5 8 13 21 34 55

Saturday, May 16, 2009

Java Design Patterns I

Here is a list of the most widely used design patterns in Java. I will write down about the details in my subsequent posts.

1. Creational  Patterns

  • Abstract Factory
  • Builder
  • Factory Method
  • Prototype
  • Singleton

2. Structural Patterns

  • Adapter
  • Bridge
  • Composite
  • Decorator
  • Facade
  • Flyweight
  • Proxy

3. Behavioural Patterns

  • Chain of Responsibility
  • Command
  • Interpreter
  • Iterator
  • Mediator
  • Memento
  • Observer
  • State
  • Strategy
  • Template Method
  • Visitor

4. J2EE Patterns

  • MVC
  • Business Delegate
  • Composite Entity
  • Data Access Object
  • Front Controller
  • Intercepting Filter
  • Service Locator
  • Transfer Object