Friday 22 August 2014

5 main differences between HashTable and HashMap

HashMap and Hashtable both implement java.util.Map interface but there are some differences that Java developers must understand to write more efficient code.

1)One of the major differences between HashMap and Hashtable is that HashMap is non-synchronized whereas Hashtable is synchronized, which means Hashtable is thread-safe and can be shared between multiple threads but HashMap cannot be shared between multiple threads without proper synchronization. 

2)The HashMap class is roughly equivalent to Hashtable, except that it permits nulls. (HashMap allows null values as key and value whereas Hashtable doesn’t allow nulls).

3) The third significant difference between HashMap vs Hashtable is that Iterator in the HashMap is a fail-fast iterator while the enumerator for the Hashtable is not and 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. This is also an important difference between Enumeration and Iterator in Java.

4)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. So if you don’t need synchronization and HashMap is only used by one thread, it out perform Hashtable in Java.

5)HashMap does not guarantee that the order of the map will remain constant over time.

Note that HashMap can be synchronized by
Map m = Collections.synchronizedMap(hashMap);
    You might like :
    Static varibale,static class,Static method
    Read More »

    Thursday 21 August 2014

    Java Collections - Map

    Map is an interface which is not derived from Collections interface as described in our previous post Java Collections. Map follows its own hierarchy .
    It stores a key -value pair in which key should be unique and value can be anything related.
    We use put method to store key-value pair in Map.

    Can we Store Null key and value in Map?
    Yes, we can store single null and corresponding null value in Map

    Example of simple map :


    import java.util.*;

    public class MapDemo {

       public static void main(String[] args) {
          Map m1 = new HashMap(); 
          m1.put("Zara", "8");
          m1.put("Mahnaz", "31");
          m1.put("Ayan", "12");
          m1.put("Daisy", "14");
          System.out.println();
          System.out.println(" Map Elements");
          System.out.print("\t" + m1);
       }


    Output : 

    Map Elements
            {Mahnaz=31, Ayan=12, Daisy=14, Zara=8}

    where Zara,Mahnaz ,Daisy ,Ayan are keya and corresponding are their values.

    How to reverse a string in java
    Implementations of Map:

    There are three implementations of Map.
    1.TreeMap
    2.HashMap
    3.Linked Hash Map

    Order of map elements in iteration 

    The order of the elements obtained from a Map depends on the type of Map they came from.

    TreeMap
    The elements are ordered by key.

    HashMap
    The elements will be in an unpredictable, "chaotic", order.

    LinkedHashMap
    The elements will be ordered by entry order or last reference order, depending on the type of LinkedHashMap.



    Detailed description of Tree map:
    present in Java.util.TreeMap class which is an implementation of Map.

    Gives surety of sorting of elements.

    Provides efficient means of adding key value pair and retrieving elements.

    You might also like :

    How to reverse a string in java



    Read More »

    Sorting of ArrayList

    Sorting of an array list is one of main tasks of a developer. There are mainly two ways to sort an array list.
    1. Using natural order
    2. Using Comparator interface .

    For both methods we will use sort () method which is defined in Collections utility class.


    See :
    How to reverse a string in java
    How to sort an Array List without using Comparator or sort method
    Oveeriding of static method in java
    Overriding
    Difference between Application Server and Web server 
    Read More »

    Wednesday 20 August 2014

    Java Collections -Set

    Set a Collection used to store Unordered but unique elements.
    If you try to store a duplicat element in a set it will throw an error.
    
    Example of set 
    
    Set setA = new HashSet();
    
    String element = "element 1";
    
    setA.add(element);
    
    System.out.println( set.contains(element) );
    
    Implemenation of set 
    
    Since Set is an interface you need to instantiate a concrete implementation of the interface in order to use it. You can choose between the following Set implementations in the Java Collections API
    1. HashSet
    2. EnumSet
    3. TreeSet
    4. LinkedHashSet
    
    How to reverse a string in java
    
    HashSet: HashSet is backed by a HashMap. It makes no guarantees about the sequence of the elements when you iterate them. 
    
    eg. Set setB = new HashSet();
    
    
    LinkedHashSet : LinkedHashSet differs from HashSet by guaranteeing that the order of the elements during iteration is the same as the order they were inserted into the LinkedHashSet. 
    Reinserting an element that is already in the LinkedHashSet does not change this order.
    
    Set setC = new LinkedHashSet();
    
    TreeSet :TreeSet also guarantees the order of the elements when iterated, but the order is the sorting order of the elements. In other words, the order in which the elements whould be sorted if you used a Collections.sort() on a List or array containing these elements. This order is determined either by their natural order (if they implement Comparable), or by a specific Comparator implementation.
    eg :Set setD = new TreeSet();
    
    
    
    
    
    
    You may Like :
    Read More »

    Tuesday 19 August 2014

    How to iterate through list in java



    List is a collection in java used to store Ordered objects which can be duplicate. List can be used to store either primitive data type or instances of a defined class. how to store object /instance of a class you can read here.

    There are 4 different ways to iterate through a list:
    1. With for loop
    2. Using advanced for loop
    3. using iterator or list iterator
    4. using do-while loop
    Using for Loop

    The basic loop can be used to iterate through a list 
    Example : Suppose we have a list of car which includes name of cars .Names can be retrieved with the help of for loop 


    package test;

    import java.util.ArrayList;
    import java.util.List;
    import java.util.ListIterator;

    public class MainS {


    public static void main(String[] args) {



    List carNames= new ArrayList();
    carNames.add("skoda");
    carNames.add("bmw");
    carNames.add("jaguar");
    for (int i = 0; i < carNames.size(); i++) {
    System.out.println(carNames.get(i));
    }

    }
    See :How to sort an Array List without using Comparator or sort method


    2. Using advanced for loop


    package test;

    import java.util.ArrayList;
    import java.util.List;

    public class testing {

        public static void main(String[] args) {
             List carNames= new ArrayList();
               carNames.add("skoda");
               carNames.add("bmw");
               carNames.add("jaguar");
        for(Object l :carNames)  
        {
             System.out.println(l);
              
        }
              
             }

        }
       


        Working :

    for(Object l :carNames)  
        {
             System.out.println(l);
              
        }

    Here we took List carNames= new ArrayList();
    CarNames list is not of any specific datatype means String ,Integer etc so its storing objects with value skoda,bmw etc.

    So while reteriving we used for(Object l :carNames)to retrieve elements.

    If you use for(String l :carNames)then it will compilation error because carNames list contains object elements not of String or any other datatype.

    If you want to retrieve using a datatype then you must need to specify datatype while declaring the list as

    List<String> carNames= new ArrayList<String> ();
                                          OR
    List<Integer> carNames= new ArrayList<Integer> ();
                     OR
    ArrayList<String> carNames= new ArrayList<String> ();
                                               OR
    Whatever you want :D

    Then you can retrieve elements as

     for(String l :carNames)
             OR
    for(Integer l :carNames)
             

    This is very normal …. I want to do something very cool like want to store all type of data objects in one list not a single Generic type.
    Like I want to store Integer ,String, Object of a class in one list … yeahhh J
    Following is the example for the same :
    package test;

    import java.util.ArrayList;
    import java.util.List;

    public class testing {

        public static void main(String[] args) {
             List<Object> carNames= new ArrayList<Object>();
    /* Or List carNames= new ArrayList();
               carNames.add(new Integer(1));
               carNames.add(new String("Hello"));
               carNames.add("jaguar");
               carNames.add(new Double(10.5));
        for(Object l :carNames)  
        {
             System.out.println(l);
              
        }
              
             }

        }
       
       
    That’s coolll !!!!

    Output :

    Using Iterator :



    package test;

    import java.util.ArrayList;
    import java.util.List;

    public class testing {

        public static void main(String[] args) {
             List<Object> carNames= new ArrayList<Object>();
    /* Or List carNames= new ArrayList();
               carNames.add(new Integer(1));
               carNames.add(new String("Hello"));
               carNames.add("jaguar");
               carNames.add(new Double(10.5));
    Iterator i= carNames.iterator;

        while(i.hasnext())  
        {
             System.out.println(i.next());
              
        }
              
             }

        }
       

    using do-while loop :


    package test;

    import java.util.ArrayList;
    import java.util.List;

    public class testing {

        public static void main(String[] args) {
             List<Object> carNames= new ArrayList<Object>();
    /* Or List carNames= new ArrayList();
               carNames.add(new Integer(1));
               carNames.add(new String("Hello"));
               carNames.add("jaguar");
               carNames.add(new Double(10.5));
    Iterator i= carNames.iterator;

          do
        {
             System.out.println(i.next());
              
        }while(i.hasnext())
              
             }

        }

    See also :
    How to reverse a string in java
    Difference between Arrays.sort() and collections.sort() 
    Custom Exception in Java -Tutorial
    5 main differences between HashTable and HashMap
    Difference between String,StringBuilder and String Buffer
    Static varibale,static class,Static method





    Read More »

    How Objects are stored in heap and Stack in java


    HEAP AND STACK IN JAVA




    1. Stack is memory in computer which is used to store temporary information. For eg. variables are stored on stack.
    2.Information after the method is done with its execution.
    3. Stack is non- shared memory which means that data of a particular thread stored on stack can be seen only by the owner of data.

    Overriding/method Overriding In java

    Which variables are stored where?

    Life Cycle of a thread 

    There are mainly three types of variables:

    1.Instance variables.
    2. Static variables.
    3. Primitive or local variables.


    Storage:

    Instance variables : Objects and its instance variable are stored in heap (young generation area).

    Primitive or local variables : Stack

    Methods :Stack 

    Reference of objects  : on stack

    Static variable and static methods: on Permanent Generation area of heap










    Heap
     1. Heap is mainly used to store objects.
    2. Its a shared memory.
    3. Both class instances and arrays are stored on heap.
    4. This area of memory is shared by all threads.




    You might interested in :

    Android Hello World Program
    Life Cycle of a thread 
    Custom Exception in Java -Tutorial
    Difference between equals() and = =
    Read More »

    Saturday 16 August 2014

    How to add List to another List

    How to reverse a string in java

    package test;

    import java.util.ArrayList;
    import java.util.List;
    import java.util.ListIterator;

    public class MainS {


    /* we have two lists as l and b and will add and reterieve list l to b */
    public static void main(String[] args) {
    List l= new ArrayList();
    l.add("1");
    l.add("2");
    List b= new ArrayList ();
    b.addAll(l);

    ListIterator lt= b.listIterator();
    while(lt.hasNext())
    {
    System.out.println(lt.next());
    }


    }


    }


    See :

    Android Hello World
     How Objects are stored in heap and Stack in java
    Internal Working Of ArrayList
    How to sort an Array List
    5 main differences between HashTable and HashMap
    Overriding/method Overriding In java
    Read More »

    How to add instance of a class to list and then retrieve it

    Suppose we have a class Car with 2 properties Car model and car name.
    We want to add instances of this class to a list so that later we can retrieve it.

    See :

    How to sort an Array List without using Comparator or sort method
    Overriding/method Overriding In java
    Difference between Application Server and Web server 

    Car.java
    package test;

    public class Car {

    private String carName;
    private String carModel;
    public Car()
    {

    }
    public String getCarName() {
    return carName;
    }
    public void setCarName(String carName) {
    this.carName = carName;
    }
    public String getCarModel() {
    return carModel;
    }
    public void setCarModel(String carModel) {
    this.carModel = carModel;
    }


    }

    Difference between LinkedList and ArrayList
    Difference between Arrays.sort() and collections.sort() 
    How to reverse a string in java
    ----------------------------------------------

    main.java

    package test;

    import java.util.ArrayList;
    import java.util.List;
    import java.util.ListIterator;

    public class MainS {

    public static void main(String[] args) {
    Car car1= new Car();
    car1.setCarName("skoda");
    car1.setCarModel("2005");
    Car car2 = new Car();
    car2.setCarName("limo");
    car2.setCarModel("2006");
    List carList= new ArrayList<Car>();
    carList.add(car1);
    carList.add(0, car2);
    ListIterator l =  carList.listIterator();
    while (l.hasNext())
    {
    Car c=(Car) l.next();
    System.out.println(c.getCarModel());
    System.out.println(c.getCarName());
    }
    }
    }

    Exception Handling in Java
    Static varibale,static class,Static method
    Read More »

    List in java Collection

    List :

    It is an interface inheritd from Collections for ordered collection of objects.
    It can contain duplicate elements.

    How is ArrayList different from Array?


    Array
    Is not definite in size. Can expand according to requirement.
    Is definite in size.
    Stores objects
    Store primitive data.
    Is present in collections
    framework Present in lang package

    See :How to sort an Array List without using Comparator or sort method


    For internal working of Array List Read: Internal worling of ArrayList

    How to convert an array to a list?

    using Arrays.asList() method.


    ArrayList and LinkedList 



    Array List and Link List are two classes that implements List Interface .

    ArrayList -> is an array based representation of list.
    Can be accessed using get and set methods.
    Used for simple sequence.

    Linked List->
    Based on Link List representation.
    Give good performance with add() and remove()n methods.
    Gives poor performance with get() set() methods.


    List Iterator

    Implements Iterator interface.

    List Iterator methods -> 
    1.hasnext()
    2. next()
    3. hasprevious()
    4. previous
    5. nextindex();
    6. previousindex();
    7. remove()
    8. add();
    9. set()


    See :Java Collection-Set
    Static varibale,static class,Static method
    Read More »

    Java Collections- Everything you want to know

    Collection is an interface - is a framework which allows for using and manipulating collections.


    Two interface trees, one starting with Collection and including Set, SortedSet, List, and Queue, and the other starting with Map and including SortedMap.

    Set- A collection that cannot contain duplicate elements.
    2. Elements are in unordered manner.

    List- A collection that can contain duplicate elements.
    Elements are in ordered manner.

    Read more about List here


    Map and HashMap
    Map is a n interface and Hash Map is class that implements it.

    Iterator:1. Used to iterate over collections.
    2. Move only in forward direction.

    List Iterator : Used to iterate over List Collection specifically.
    2. can traverse in both forward and backward direction.

    Read More »

    Thursday 14 August 2014

    Hibernate Interview Questions

    1. Call Back Interfaces


    These interfaces are helpful to receive notifications about changing state of an object such as saved , loaded , deleted.
    There is no need to implement callback interfaces in hibernate.

    2. which connection pooling is by default supported by hibernate.

    c3p connection pooling.

    3. states of an object in hibernate .

    1. persistence - when an object is attached to a hibernate session.Any changes in this object will be reflected on database either upon automatic flush or using session.flush() method.
    2. Detached- An object which was previously attached to a session but not now.This object can be reattached to a session using session.merge() method,save(),saveorupdate() methods.
    3. Transient -This is a newly created object which was never attached to a session .Persist () or save() method sends this object to persistence state.




    Read More »