Thursday, March 8, 2012

Java HashMap Example

The HashMap class uses a hash table to implement the Map interface. This allows the execution time of basic operations, such as get() and put(), to remain constant even for large sets.

The following constructors are defined:  
HashMap( )
HashMap(Map m)
HashMap(int capacity)
HashMap(int capacity, float fillRatio)

 

Hash map does not guarantee the order of its elements. Therefore, the order in which elements are added to a hash map is not necessarily the order in which they are read.

Here is the code:
 
import java.util.HashMap;
import java.util.Map;

/**
 *
 * This Java HashMap example describes the basic operations performed on the HashMap
 * @author abdul
 *
 */
public class HashMapExample {
    public static void main(String args[]){
       
        // constructs a new empty HashMap with default initial capacity       
        Map<Integer,String> hashMap = new HashMap<Integer,String>();
      
        // adding value into HashMap
        hashMap.put(new Integer(1),"DELL");
        hashMap.put(new Integer(2),"SONY");
        hashMap.put(new Integer(3),"LENOVO");
        hashMap.put(new Integer(4),"SAMSUNG");
        hashMap.put(new Integer(5),"HP");
    
        //To get the size of HashMap       
        System.out.println("HashMap Size: " + hashMap.size());
     
        // To Find particular value from the HashMap:
        if(hashMap.containsValue("HP")){
            System.out.println("HashMap contains HP");
        }else{
            System.out.println("HashMap does not contain HP");
        }
      
        //To find particular key in HashMap
        if( hashMap.containsKey(new Integer(2)) ){
            System.out.println("HashMap contains key");
        }else{
            System.out.println("HashMap does not contain key");
        }
      
        /*
        Use get method of HashMap to get value mapped to particular key.       
        Signature of the get method is,       
        Object get(Object key)       
        */
      
        String value = hashMap.get(new Integer(5));       
        System.out.println("Value : " + value);

        //To get the key value pair of hashMap
        for (Map.Entry<Integer, String> entry1 : hashMap.entrySet()) {
            Integer key = entry1.getKey();
            String data = entry1.getValue();
            System.out.println("key value : " + key + "\t" + data );

        }
 
        // To remove something from the hashmap      
        System.out.println( hashMap.remove(new Integer(4)) + " removed from the hashMap");
       
        //Display value of HashMap
        System.out.println("HashMap : " + hashMap );
    }
}

Output:
HashMap Size: 5
HashMap contains HP
HashMap contains key
Value : HP
key value : 1    DELL
key value : 2    SONY
key value : 3    LENOVO
key value : 4    SAMSUNG
key value : 5    HP
SAMSUNG removed from the hashMap
HashMap : {1=DELL, 2=SONY, 3=LENOVO, 5=HP}

How to get free disk space of a drive in java ?

JDK 1.6 provides few new methods  getTotalSpace(),getFreeSpace(), bundled with java.io.File. These methods provides essential information regarding disk space.

getFreeSpace() method-   Returns the number of unallocated bytes in the partition named by this abstract path name.
getTotalSpace() method - Returns the size of the partition named by this abstract pathname.


Here is the code: 

import java.io.File;

/**
 * Program that returns the number of unallocated bytes , total space in the partition.
 *
 * @author abdul
 *
 */
public class DiskDetail {
    public static void main(String[] args) {
        File file = new File("C:");
        long totalSpace = file.getTotalSpace(); // total disk space in bytes.
        long freeSpace = file.getFreeSpace(); // unallocated / free disk space
        long  diskUsage = (totalSpace - freeSpace);
       
        System.out.println("Total size : " + totalSpace + " bytes");
        System.out.println("Space free : " + freeSpace + " bytes");
        System.out.println("Used Space : " + diskUsage + "bytes");
    }
}

Output:
Total size : 107373129728 bytes
Space free : 44510306304 bytes
Used Space : 62862823424bytes

Reference: 

http://docs.oracle.com/javase/6/docs/api/java/io/File.html 


 

Friday, February 24, 2012

JAXB - II (jaxb.index file and ObjectFactory)

I was getting a Exception like, javax.xml.bind.JAXBException: "doesnt contain ObjectFactory.class or jaxb.index" while trying to create a JAXBContext using JAXBContext.newInstance(String contextPath).

It took me a while to figure out what went wrong. So now that I've got things working correctly, I thought I'd post this example and solution to hopefully save you some time.

When we create a marshaller, we first need to create a JAXBContext via its newInstance() factory method. You can create a context for a specific JAXB class  or you can create a context for a list of packages.

There are two ways to resolve this issue : 
  - By creating ObjectFactory
  - By adding jaxb.index file

jaxb.index :

The jaxb.index file is a text file contains a listing of the classes on the containing package that have JAXB annotations.
Note : The name of the clases is their simple name not their classified name.
 

Rather than creating a ObjectFactory, I guess adding a jaxb.index file is much easy part. Just you need to add class names to the file and place the file in the package (directory) where your JAXB annotated classes reside.
Its just the class name, not the fully qualified name (the package name is determined by the directory you placed the file in) or the.class name.

     JAXBContext context = JAXBContext.newInstance(className.getClass().getPackage().getName());

If the package following package does not have jaxb.index file, this change will cause the test to throw the JAXBException. Add the file and everything works great.

How TOPT Works: Generating OTPs Without Internet Connection

Introduction Have you ever wondered how authentication apps like RSA Authenticator generate One-Time Passwords (OTPs) without requiring an i...