Wednesday 15 May 2013

Program to create a Linked List in Java


class Link {
    public int data1;
    public Link nextLink;

    //Link constructor
    public Link(int d1) {
   data1 = d1;
    }

    //Print Link data
    public void printLink() {
   System.out.print("{" + data1 + "} ");
    }
}

class LinkList {
    private Link first;

    //LinkList constructor
    public LinkList() {
   first = null;
    }

    //Returns true if list is empty
    public boolean isEmpty() {
   return first == null;
    }

    //Inserts a new Link at the first of the list
    public void insert(int d1) {
   Link link = new Link(d1);
   link.nextLink = first;
   first = link;
    }

    //Deletes the link at the first of the list
    public Link delete() {
   Link temp = first;
   first = first.nextLink;
   return temp;
    }

    //Prints list data
    public void printList() {
   Link currentLink = first;
   System.out.print("List: ");
   while(currentLink != null) {
   currentLink.printLink();
   currentLink = currentLink.nextLink;
   }
   System.out.println("");
    }
}  

class LinkListTest {
    public static void main(String[] args) {
   LinkList list = new LinkList();

   list.insert(1);
   list.insert(2);
   list.insert(3);
   list.insert(4);
   list.insert(5);

   list.printList();

   while(!list.isEmpty()) {
   Link deletedLink = list.delete();
   System.out.print("deleted: ");
   deletedLink.printLink();
   System.out.println("");
   }
   list.printList();
    }
}

Monday 6 May 2013

Difference between HashMap and Hashtable in Java


  • HashMap allows null values as key and value whereas Hashtable doesn't allow nulls 
  • HashMap is non synchronized whereas Hashtable is synchronized.  
  • Java 5 introduces ConcurrentHashMap which is an alternative of Hashtable and provides better scalability than Hashtable in Java. 
  • Iterator in the HashMap is  a fail-fast iterator  while the enumerator for the Hashtable is not. 
  • HashMap throw ConcurrentModificationException if any other Thread modifies the map structurally  by adding or removing any element except Iterator's own remove() method.  
  • But this is not a guaranteed behavior and will be done by JVM on best effort. 
  • One more notable difference between Hashtable and HashMap is that because of thread-safety and synchronization Hashtable is much slower than HashMap if used in Single threaded environment.  
  • HashMap does not guarantee that the order of the map will remain constant over time.

Difference between ConcurrentHashMap and Collections.synchronizedMap


  • ConcurrentHashMap is designed for concurrency and improve performance while HashMap which is non synchronized by nature can be synchronized by applying a wrapper using Collections.synchronizedMap 
  • ConcurrentHashMap do not allow null keys or null values while HashMap allows null keys. 
  • In case of multiple reader and Single writer ConcurrentHashMap is best choice.

Difference between ConcurrentHashMap and Hashtable?


  • Both can be used in multithreaded environment but once the size of Hashtable becomes considerable large performance degrade because for iteration it has to be locked for longer duration. 
  • Since ConcurrentHashMap introduced concept of segmentation , how large it becomes only certain part of it get locked to provide thread safety so many other readers can still access map without waiting for iteration to complete. 
  • In Summary ConcurrentHashMap only locked certain portion of Map while Hashtable lock full map while doing iteration.

Enumeration vs Iterator or Difference between Enumerator and Iterator.


  • Enumeration is older and its there from JDK1.0 while iterator was introduced later.  
  • Functionality of Enumeration interface is duplicated by the Iterator interface. 
  • Only major difference between Enumeration and iterator is Iterator has a remove() method while Enumeration doesn't. 
  • Enumeration acts as Read-only interface, because it has the methods only to traverse and fetch the objects. 
  • By using Iterator we can manipulate the objects like adding and removing the objects from collection e.g. Arraylist. 
  • Also Iterator is more secure and safe as compared to Enumeration because it  does not allow other thread to modify the collection object while some thread is iterating over it and throws ConcurrentModificationException.  
  • Both Enumeration and Iterator will give successive elements, but Iterator is new and improved version where method names are shorter, and has new method called remove.

What is difference between fail-fast and fail-safe Iterators?



  • Fail-fast Iterators throws ConcurrentModificationException when one Thread is iterating over collection object and other thread structurally modify Collection either by adding, removing or modifying objects on underlying collection. 
  • They are called fail-fast because they try to immediately throw Exception when they encounter failure. 
  • On the other hand fail-safe Iterators works on copy of collection instead of original collection so they dont throw any Exceptions.


What happens On HashMap in Java if the size of the HashMap exceeds a given threshold defined by load factor ?


  • If the size of the Map exceeds a given threshold defined by load-factor e.g. if load factor is .75 it will act to re-size the map once it filled 75%.  
  • Similar to other collection classes like ArrayList,  Java HashMap re-size itself by creating a new bucket array of size twice of previous size of HashMap , and then start putting every old element into that new bucket array.  
  • This process is called rehashing because it also applies hash function to find new bucket location. 

How will you retrieve Value object if two Keys will have same hashcode?


  • We will call get() method and then HashMap uses Key Object's hashcode to find out bucket location. 
  • After finding bucket location , we will call keys.equals() method to identify correct node in LinkedList and return associated value object for that key in Java HashMap.

What will happen if two different objects have same hashcode?


  • We know that equals() and hashCode() contract  that two unequal object in Java can have same hashcode.  
  • Since hashcode is same, bucket location would be same and collision will occur in HashMap. 
  • Since HashMap use LinkedList to store object, this entry (object of Map.Entry comprise key and value )  will be stored in LinkedList.  
  • There are many collision resolution methods available this is simplest and HashMap in Java does follow this. 

How HashMap works in java? or How does get () method of HashMap works in Java?


  • HashMap works on principle of hashing. 
  • When we pass Key and Value object  to put() method on Java HashMap, HashMap implementation calls hashCode method on Key object and applies returned hashcode into its own hashing function to find a bucket location for storing Entry object. 
  • Important point to mention is that HashMap in Java stores both key and value object as Map Entry in bucket which is essential to understand the retrieving logic.  
  • If people fails to recognize this and say it only stores Value in the bucket they will fail to explain the retrieving logic of any object stored in Java HashMap. 

Friday 3 May 2013

What is the difference between creating String as new() and literal?


When we create string with new() Operator, it’s created in heap and not added into string pool while String created using literal are created in String pool itself which exists in PermGen area of heap.

String s = new String("Test");
 

does not  put the object in String pool , we need to call String.intern() method which is used to put  them into String pool explicitly. its only when you create String object as String literal e.g. String s = "Test" Java automatically put that into String pool.

Thursday 2 May 2013

Difference between Vector and ArrayList in java?


  • All the methods of Vector is synchronized. 
  • But, the methods of ArrayList is not synchronized. All the new implementations of java collection framework is not synchronized.
  • Vector and ArrayList both uses Array internally as data structure. 
  • They are dynamically resizable. 
  • Both ArrayList and Vector maintains the insertion order of element.
  • Difference is in the way they are internally resized. 
  • By default, Vector doubles the size of its array when its size is increased. 
  • ArrayList increases by half of its size when its size is increased.
  • Therefore as per Java API the only main difference is, Vector’s methods are synchronized and ArrayList’s methods are not synchronized.
  • In general, executing a ‘synchronized’ method results in costlier performance than a unsynchronized method. Keeping the difference in mind, using Vector will incur a performance hit than the ArrayList. 
  • But, when there is a certain need for thread-safe operation Vector needs to be used.


Wednesday 1 May 2013

Difference between ==, equals and hashcode in java


String s1= new String("abc");
String s2= new String("abc");
String s3 ="abc";
System.out.println(s1==s3);
System.out.println(s1==s2);
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));
System.out.println(s1.hashCode());
System.out.println(s2.hashCode());
System.out.println(s3.hashCode());

Output is: false false true true 96354 96354 96354


==  Compares real equality of Objects (i.e) both references should point to the same object, not their content. 
.equal Compares content of a object.            String a = new String("aa");
    String b = new String("aa");
 
           a and b are pointing to different objects.
Hashcode  If objects are equal then their hashchodes must be the same, but if hashcodes are the same, it doesn't mean that objects are equal.