Thursday, 17 August 2017

What is the advantage of iterating Collection using iterator?

We can use for loop, advanced for loop or iterator for iterating over Collection.

But using iterator over other competitors gives some advantages like:

  • By using for loop you cannot update(add/remove) the Collection whereas with iterator we can easily update Collection.
Example for updating list by iterator:

package javaRadarArrayList;

import java.util.ArrayList;
import java.util.Iterator;

public class UpdateList {

      public static void main(String[] args) {
            //create Array List
            ArrayList<String> javaRadarList = new ArrayList<String>();
            //Add elements to ArrayList
            javaRadarList.add("Java");
            javaRadarList.add("Spring");
            javaRadarList.add("Hibernate");
            javaRadarList.add("EJB");

            System.out.println("Original list:" +javaRadarList);
           
            Iterator<String> itr = javaRadarList.iterator();
            while(itr.hasNext()){
                  String token = itr.next();
                  itr.remove();
                  System.out.println("list afer modification:" +javaRadarList);
            }
                 
      }

}

OUTPUT:
Original list:[Java, Spring, Hibernate, EJB]
list afer modification:[Spring, Hibernate, EJB]
list afer modification:[Hibernate, EJB]
list afer modification:[EJB]
list afer modification:[]


NOTE: Try to remove object from Collection using for loop and see if you can or not.

  • In situations where there is no idea of what type of Collection will be used we can use iterator to traverse over the collection as all Collection implements iterator interface.

Sunday, 13 August 2017

Difference: HashMap vs HashTable


HashMap and HashTable differ based on the following parameters:

  • Nature
           HashMap is not synchronized in nature.
           HashTable is synchronized in nature

  • Traversed by
           HashMap can be traversed by using an iterator
           HashTable can be traversed by using an iterator or enumerator

  • Null value/key
          HashMap allows only one null key and any number of null values.
          HashTable doesn't allow key or value as null.

  • fail-fast nature of iterator
          Iterator in HashMap is fail-fast.
          Enumerator in HashTable is not fail-fast.

  • Performance
          HashMap is faster performance wise.
          HashTable is slower in comparision to HashMap performance wise.
          
          Reason: Since HashTable is synchronized in nature so it doesn't allow multi-threading                                       operation on a particular resource at a time thus turning out to be slower than                                       HashMap which is non-synchronized by nature.



You may also like to read:



Saturday, 12 August 2017

Ten common java interview question


Today I am going to share with my readers the ten commonly asked interview questions in java interview. These questions are based on survey that I conducted on my friends who were attending interview of different companies.

This survey was conducted majorly on candidates having 1-4 years of experience in java.

Iterator is considered fail-fast as it will fail immediately if it feels that the Collection on which it is iterating currently is about to get modified by self/another thread. Here modification means addition, deletion or updating of element. And this modification may result in non-deterministic behavior at an undetermined time in future. In such cases, iterator fails by throwing  ConcurrentModificationException. Click to learn more with example

String is immutable. A detailed explanation citing the reason behind this immutability is already written in this article




We know String is immutable in java. So to perform modification on String we use either StringBuffer or StringBuilder. Though they perform same task but still they differ on certain parameters. Lets check out the difference here



This is one of the most frequently asked java interview question. You will use either of them while coding number of times.
So lets take a walk through to the difference between the two.

First thing that you should be aware of is that both are used to compare two objects. But this question is generally asked in relation to String because each of them when used to compare String Objects behaves differently. Lets see the detailed explanation here

Array list and Linked list both implements list interface. Now if you have to use one then which one will you prefer. For this we have to think about the number of elements we have to insert or delete from the list, memory consumption, which will help in searching the element faster, etc. Click to read more...

Sunday, 30 July 2017

Why iterator is fail fast in java?

Iterator is considered fail-fast. 
Reason:  
It is so because iterator will fail immediately if it senses that the Collection on which it is iterating currently is about to get modified by another thread or by itself. Here modification means addition, deletion or updating of element. And this modification may result in non-deterministic behavior at an undetermined time in future. In such cases, iterator fails by throwing  ConcurrentModificationException.

Let's look at example that shows iterator's fail-fast nature:
package FailFastIterator;

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

public class FailFastItr {

      public static void main(String[] args) {
            List<String> rajneeshList = new ArrayList<String>();
            rajneeshList.add("Java");
            rajneeshList.add("C++");
            rajneeshList.add("Python");

            Iterator<String> itr = rajneeshList.iterator();

            while(itr.hasNext()){
                  String token = itr.next();
                  System.out.println(token);
                  if(token.equals("Python")){
                        rajneeshList.remove(token);  //trying to remove while iteration is going on...
                  }                
            }
            System.out.println("After modification :"+rajneeshList);

      }


}
OUTPUT:

Java
C++
Python
Exception in thread "main" java.util.ConcurrentModificationException
      at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
      at java.util.ArrayList$Itr.next(Unknown Source)
      at FailFastIterator.FailFastItr.main(FailFastItr.java:18)




In the above code you can see that as Collection thread tries to remove element while iteration is on, iterator immediately fails by throwing ConcurrentModificationException. 

You can notice here that even it doesn't print,

System.out.println("After modification :"+rajneeshList);

which is outside while loop and fails immediately at the time of Collection modification. 




You may also like to read about:


Saturday, 10 June 2017

ArrayList in java


ArrayList is a class that extends AbstractList class and implements List interface in java. 

It uses dynamic array for storing the elements thus gaining upper hand in comparison to Array (which is static in nature and has fixed length).


Key feature of ArrayList:

1. It implements List interface, RandomAccess interface, Collection interface, Iterable interface, Cloneable interface and Serializable interface.
2. It is a part of java.util package.
3. ArrayList can expand and shrink automatically as per the need because of its dynamic array storage capability.
4. ArrayList is not synchronized (else it would have been roughly equivalent to Vector).
5. It permits all element, including null.
6. ArrayList is generally slow while manipulating the elements as during insertion or deletion lot of shifting needs to be done.


Now let’s look at the ways in which you can create ArrayList in java. 

·         ArrayList<E> myList = new ArrayList <E>();     //<E> denotes generics
·         ArrayList<E> myList = new ArrayList <E>(Collection c);//<E> denotes generics

Simple Example:


package javaRadarArrayList;

import java.util.ArrayList;

public class SimpleArrayList {

      public static void main(String[] args) {
            //create Array List
            ArrayList<String> javaRadarList = new ArrayList<String>();
            //Add elements to ArrayList
            javaRadarList.add("Java");
            javaRadarList.add("Spring");
            javaRadarList.add("Hibernate");
            javaRadarList.add("EJB");

            System.out.println(javaRadarList);
      }


}




Now let’s look at different ways in which you can use the ArrayList that you created. 
Click on each link to read about them.

ArrayList operations

·         Sort the elements in ArrayList
·         Search element in ArrayList

Traverse ArrayList


Convert

·       ArrayList to LinkedList



ArrayList or LinkedList. Which one to use?(Click to see the difference between two and decide)


How to synchronize ArrayList?

So far we have learned that ArrayList is non-synchronized but still what to do if we need to synchronize it.
So java provides a solution to synchronize your ArrayList. Use synchronizedList() method provided by Collections utility class.

                Collections.synchronizedList(List list)


-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
If you are looking for a reference book on java then we recommend you to go for → Java The Complete Reference
Click on the image link below to get it now.