Friday, September 27, 2013

HashMap Vs HashTable


HashMap
HashTable
HashMap & HashTable
Implements Map interface
Implements Map interface
Both Implements  Map interface
HashMap is not  Synchronized.

HashTable is Synchronized .


Not thread-safe, need to implement proper synchronization for multithreading.
In Java 5 we have ConcurrentHashMap, which is thread safe.
HashTable is Thread-safe, shared between multiple threads.

Faster than HashTable.
Better for non-threaded applications.
Much Slower than HashMap for single thread use.
(Synchronization makes HashTable slow)

HashMap allows null.
One  null Key and any number of  null values.
(so do the correct null check for HashMap. See the Null pointer exception in HashMap for details)
HashTable Doesn’t allow null keys or values.

Iterator in the HashMap is fail-fast iterator.


Enumerator in the HashTable is not fail-fast.

Doesn’t retain order.
Java.util.HashMap is unordered
Need to use  LinkedHashMap to maintain order.
Doesn’t retain order.
Both are using hash function  to store and retrieve values from the map.

HashMap is not Synchronized

HashMap is not synchronized. 
If  your code is executing in Single threaded environment it is better to use  HashMap.
But in the case of multi-threaded environment, your code will be shared among multiple threads.Here we need some way to ensure that the resource will be used  by only one thread at a time.Here we need synchronization of objects.
If your code is synchronized, it will executed by only one thread at a time.
In this case if your using HashMap, you need to do something to synchronize the HashMap.

Or you can use HashTable or ConcurrnetHashMap(From Java 5 onwards).

Synchronzing the HashMap
To synchronize HashMap we can use a method from collection API Collections.synchronizedMap().
  Map map = Collections.synchronizedMap(new HashMap());

HashMap is fail-fast

Fail-fast means when you try to modify the contents of HashMap when you are iterating through it, it will fail and throw ConcurrentModificationException.

       HashMap hm = new HashMap<String, String>();
        hm.put("A","1");
        hm.put("B","2");
        hm.put("C","3");
       String i;
       Set Keys = hm.keySet();
       for(Object key:Keys) {
              m.put("D", "4"); // it will throw ConcurrentModificationException
      
}
O/P:
Exception in thread "main" java.util.ConcurrentModificationException

To avoid this we have to use fail-safe iterator (ConcurrentHashMap)

HashTable is not fail-fast

HashTable it is using Enumeration for Keys access.

Enumerator is introduced in older version of java, so there is no way to remove items when ever we are accessing through enumerator.
For HashTable enumeration it will not throw ConcurrentModificationException exception

HashTable hm = new Hashtable<String, String>();
               hm.put("A","1");
               hm.put("B","2");
               hm.put("C","3");
              String i;
               for (Enumeration e = hm.elements() ; e.hasMoreElements() ; e.nextElement()) {
                     hm.put("D", "4"); // will not throw any exception

              }

Friday, August 9, 2013

Null pointer exception in HashMap

1.     Don’t forget to set the hash map before using it.

 Below code will through NullPointerException
import java.util.HashMap;

public class hashnull1 {
static HashMap<String,String>hm;

  public static void main(String[] args)
   {  
      hm.put("1","Apple");
      // the hashmap ‘hm’ is not defined
   }
}

When you run the above code it will through java.lang.NullPointerException.
In the above code we declare the HashMap hm but forgot to define it,
On declaration the HashMap will be having null value without any memory allocation.

HashMap<String,String>hm equal to HashMap<String,String>hm = null;

On the defining part only the memory allocation is happening to hm.

So we need to set hm before using this.
hm = new HashMap<String, String>();

Correct code:

public class hashnull1 {
       static HashMap<String,String>hm;
          public static void main(String[] args)
          {  
                 hm = new HashMap<String, String>();
              hm.put("1","Apple");
          }

}

2.      Do the null check before using HashMap.

 In the above example we can avoid null pointer exception if we might have done null check for hm.

public class hashnull1 {
       static HashMap<String,String>hm;
          public static void main(String[] args)
          {  
                if(hm != null) //checking for null, it can avoid nullpointer ex
              hm.put("1","Apple");
          }

}

3.      Do the Null check for values from the hash map

See the below code.
public class hashnull1 {
       static HashMap<String, String> hm;

       public static void main(String[] args) {
              hm = new HashMap<String, String>();
              String a = hm.get("2"); // value of ‘a’ will be ‘Null’ since key is not there in ‘hm’
              if(a.equals("apple")) { // Since ‘a’ is null it will lead ‘Null pointer’
                     System.out.println("Apple");
              }
       }

}

In the above code try to get the value for  key “2” which is not there in hm, it will always return “null”
Also HashMap will allow null values, so always do the null check for values from the HashMap

Corrected code:
public class hashnull1 {
       static HashMap<String, String> hm;

       public static void main(String[] args) {
              hm = new HashMap<String, String>();
              String a = hm.get("2");
              if(a != null && a.equals("apple")) {
                     System.out.println("Apple");
              }
       }

}
Null values are allowed in hashmap so do the null check for values
hm.put("1", null);
a = hm.get("1");
System.out.println("a>>>"+a); // print “null”

4.     Check for the key existence in hasmap using “containsKey”

map.containsKey(key)
In the above code we can also add a check for key existence in the “HashMap” 
public class hashnull1 {
       static HashMap<String, String> hm;

       public static void main(String[] args) {
              hm = new HashMap<String, String>();
              if (hm.containsKey("2")) { // check whether the key ‘2’ is present in the ‘hm’
                     String a = hm.get("2");
                     if (a != null && a.equals("apple")) {
// hm can contain null values so need to do the null check for values
                           System.out.println("Apple");
                     }
              }
       }

}
 


Sunday, July 14, 2013

USERS in WebSphere Commerce

USERS in WebSphere Commerce

If you are working in WCS, you might have heard about registered users, guest users and generic users. Do you the difference between these users’ types?

Generic User:
When a customer accesses the website to browse the home pages and other product pages without signing in, the user will be assigned as a generic user. Normally in WCS, the user id -1002 refers to the generic user. This user id will be shared across the entire application. This approach minimizes the resource usage in WCS as the same context can be used for multiple users.

Guest User:
When the user adds an item to cart or do some activity which requires a unique identity the user will be converted to a guest user. A guest user will be assigned with a unique member id. Based on the business model and the access policies defined, a guest user will have more privileges in the site rather than a generic user.
The registrationType present in USERS table for both guest and generic user will be “G”. But in WCS by default, a generic user cannot purchase an item through the website. He should register with the site to place an order in the system. A guest user can place order in the site, if guest checkout is enabled in the system.

Registered User:
If the guest user registers to the site, the user will get converted to a registered user, and any assets that the guest user owned will be migrated to the registered user. As part of registration process, the user has to provide a unique user name and password. This will create a profile for the user and will create an entry in USERS table with profile type ‘R’. This username will be always tied up with the member id which is created during registration. Based on the customization implemented, user can store his personal, address and payment details in his profile. Also it will provide additional functionality to the user such as order history, checkout later, personalization, reminder emails etc.

The term “registered user” not only refers the customers who signin to purchase the items, but includes the site administrators, customer care representatives etc. But the registration type present in USERS table will be different for these users.  For eg. The user type of a site administrator will be ‘A’ where as for an administrator, it will be ‘S’. Based on the configuration and customization, the functionalities provided to each of these users may differ. 


How to identify different users from USERS table:



Member Id
Registration Type
Description
-1002
G
The user is a generic user
<any member id>
G
The user is a guest user
<any member id>
R
Registered customer
<any member id>
S
Site Administrator
<any member id>
A
Administrator





Wednesday, July 10, 2013

SWT Code -FileDialog,DirectoryDialog and multi-lined text field

Search for files with specified extension

Learn  how to use FileDialog,DirectoryDialog and multi-lined text field in SWT using Grid layout



/*
 *  program to get the file with specified extension.
 *
 * Description: If we gave directory path and extension of file , we will be able to select files with that specified extension
 */
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;

public class FileSearchForExtension {
       Display display = new Display();
       Shell shell = new Shell(display);
       Text text;
       String selectedDir;
       Label label;
       Text text1, fileNameText;
       String fileFilterPath = "";
       StringBuilder sb = new StringBuilder("");

       public FileSearchForExtension() {
              init();
              shell.pack();
              shell.setSize(450, 300); // setting size of the shell
              shell.open();

              while (!shell.isDisposed()) {
                     if (!display.readAndDispatch()) {
                           display.sleep();
                     }
              }
              display.dispose();
       }

       private void init() {
              shell.setText("File Searcher for Extension");
              GridLayout gridLayout = new GridLayout();
              gridLayout.numColumns = 2;
              gridLayout.makeColumnsEqualWidth = true;
              shell.setLayout(gridLayout);
              GridData data = new GridData(GridData.FILL_BOTH);

              // UI design 
              // Directory selection button and text box

              Button button = new Button(shell, SWT.PUSH);
              button.setText("Select a directory");
              text = new Text(shell, SWT.NONE);
              text.setLayoutData(data);

              // Enter extension manually
              label = new Label(shell, SWT.BORDER | SWT.WRAP);
              label.setText("Enter the extension to search");
              text1 = new Text(shell, SWT.NONE);
              text1.setLayoutData(data);

              // Multiple/single file name selection button and text box

              Button buttonSelectFile = new Button(shell, SWT.PUSH);
              buttonSelectFile.setText("Select a file/multiple files names");
              fileNameText = new Text(shell, SWT.MULTI | SWT.BORDER | SWT.WRAP
                           | SWT.V_SCROLL);
              fileNameText.setLayoutData(data);

              Button buttonClear = new Button(shell, SWT.PUSH);
              buttonClear.setText("clear fileds");
              GridData gridData = new GridData();
              gridData.horizontalAlignment = GridData.CENTER;
              gridData.horizontalSpan = 2;
              buttonClear.setLayoutData(gridData);

              // Adding listner for directory selection using directory dialog
              button.addListener(SWT.Selection, new Listener() {
                     public void handleEvent(Event event) {
                           DirectoryDialog directoryDialog = new DirectoryDialog(shell);

                           directoryDialog.setFilterPath(selectedDir);
                           directoryDialog
                                         .setMessage("Please select a directory and click OK");

                           String dir = directoryDialog.open();
                           if (dir != null) {
                                  text.setText(dir);
                                  text.setEditable(true);
                                  selectedDir = dir;
                           }
                     }
              });

              // adding listener to file names selection using file dialog
              buttonSelectFile.addListener(SWT.Selection, new Listener() {
                     public void handleEvent(Event event) {
                           FileDialog fileDialog = new FileDialog(shell, SWT.MULTI);

                           fileDialog.setFilterPath(text.getText());
                           String extension = text1.getText();
                           fileDialog
                                         .setFilterExtensions(new String[] { "*." + extension });

                           String firstFile = fileDialog.open();

                           if (firstFile != null) {
                                  fileFilterPath = fileDialog.getFilterPath();
                                  String[] selectedFiles = fileDialog.getFileNames();

                                  for (int i = 0; i < selectedFiles.length; i++) {
                                         sb.append(selectedFiles[i] + "\n");
                                  }
                                  fileNameText.setText(sb.toString());
                           }
                     }
              });

              // Adding listener to the clear button
              buttonClear.addListener(SWT.Selection, new Listener() {
                     public void handleEvent(Event event) {
                           text.setText("");
                           text1.setText("");
                           fileNameText.setText("");
                           sb.setLength(0);
                     }
              });

       }

       public static void main(String[] args) {
              new FileSearchForExtension();
       }
}