Monday, 2 January 2017

Java Difference : Iterator vs Enumeration

Iterator and Enumeration differ based on the following parameters:

1.      Introduced
Enumeration was introduced as part of JDK1.0
Iterator was introduced from JDK1.2

2.      Modifying Collection
Enumeration cannot be used to modify the elements in Collection while traversing.
Iterator can be used to remove the element in Collection while traversing (it can remove element using remove() )

3.      Available methods
Enumeration:  hasMoreElements(), nextElement()
Iterator:  hasNext(), next(), remove()

4.      Fail fast or Fail safe
Enumeration is fail safe by nature.
Iterator is fail fast by nature.

Note : Iterator being fail fast by nature is considered safe than enumeration as it throws ConcurrentModificationException, if any other thread tries to modify the Collection that is being traversed by Iterator.

5.      Legacy concept
Enumeration is generally preferred for traversing over legacy classes like Vector, HashTable, etc.
Iterator is used to traverse over almost all classes in java Collection framework like ArrayList, LinkedList, HashMap, HashSet, etc.

Note: Iterator is preferred over Enumeration. 



Example: 

package Traversal;

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

public class TraversalMethods {

      public static void main(String[] args) {
            List<String> arrayList = new ArrayList<String>();
            arrayList.add("Rajneesh");
            arrayList.add("Shweta");
            arrayList.add("Anup");

            Iterator<String> listIterator = arrayList.iterator();
            System.out.println("Traversing list using iterator");

            while(listIterator.hasNext()){

                  String token = (String)listIterator.next();
                  System.out.println(token);
                  if(token.equals("Shweta")){
                        listIterator.remove();   //iterator remove() method facility
                  }
            }
            System.out.println("ArrayList after removal operation");
            System.out.println(arrayList);

            Vector<String> vector = new Vector<String>();
            vector.add("Puja");
            vector.add("Mukesh");
            vector.add("Titli");

            System.out.println("Traversing vector using Enumeration");
            Enumeration<String> enumeration = vector.elements();

            while(enumeration.hasMoreElements()){

                  System.out.println(enumeration.nextElement());
                  //enumeration.remove(); METHOD DOESNOT EXIST
            }

      }

}


In the given example you can see iterator provides you with remove() method whereas in enumeration no such method exists.

Hope this helps. IF there is any query then put in the comment box and we can discuss it and clarify.

You may also like to read:

Wednesday, 28 December 2016

String in java

Strings are generally sequence of characters.

Java treats String as an Object.

Java has a class named String which has numerous methods using which one can perform various operation on String object. The String class is in java.lang package.

String class implements

·         Serializable interface
·         Comparable interface
·         CharSequence interface.

Create String Object

In java, String object can be created in the following two ways:

1.      String literal
String s = “Java”;

2.      By using new keyword
String s = new String(“Java”);


Most important characteristics of java String is immutability. String is immutable in java.


Tuesday, 27 December 2016

Java Basics

Java is a popular programming language as well as a platform. It was first introduced in 1995 by Sun MicroSystems.
Java can be used to develop standalone (Desktop) application, mobile application, web application, applets, games, etc.
Java SE, Java EE and Java ME are the various edition available to develop applications in java.

Significant features:

·         Java is a high level programming language.
·         Java follows Object Oriented Programming concept.
·         Java is platform independent as it is Write Once, Run Anywhere (WORA) programming language.        (Learn why?)
·         Java is a multi-threaded programming language.
·         Java is secure, robust and portable.

Previous Versions: You don’t need to remember each one of them. Only the difference between any two consecutive versions that is marked in bold needs to be known. It may be asked during interviews.

  • JDK Alpha and Beta (1995)
  • JDK 1.0 (23rd Jan, 1996)
  • JDK 1.1 (19th Feb, 1997)
  • J2SE 1.2 (8th Dec, 1998)
  • J2SE 1.3 (8th May, 2000)
  • J2SE 1.4 (6th Feb, 2002)
  • J2SE 5.0 (30th Sep, 2004)
  • Java SE 6 (11th Dec, 2006)
  • Java SE 7 (28th July, 2011)
Latest Version:

·         Java SE 8 is the latest version of java.
Requirements to get started:

·         Install the JDK in case you don’t have it on your System.
·         Install an editor like Eclipse, Netbeans, or any other as per your choice. (All the example in this tutorial is programmed on Eclipse)
·         Set path and Classpath
Let’s get started with our first Java Program.

Friday, 23 December 2016

Difference : Iterator vs ListIterator

Iterator and ListIterator differ based on following parameters:

1.      Traversal direction
Iterator allows to traverse the List, Set and Map in only forward direction. Iterator is unidirectional in nature.
ListIterator allows to traverse the List (remember only List) in both forward and backward direction. ListIterator is bidirectional.

2.      Method
Iterator has next() method, using which forward traversal is possible.
ListIterator has next() method for forward traversal and previous() method for backward traversal.

3.      Collection implementations that can be traversed
Iterator can traverse List, Set and Map.
ListIterator can only be used for List traversal.

4.      Modifying the elements while traversing
Iterator can only remove the element during iteration. It has only remove() method.
ListIterator can add, remove and set elements during iteration.

5.      Current position
Iterator cannot determine the current position of iteration during iterating over List.
ListIterator can determine the current position of iteration during iterating over List.

6.      Retrieve index
Index of the element cannot be retrieved using Iterator.
Index of the element can be retrieved using ListIterator using previousIndex() and nextIndex() method.

7.      Example

Wednesday, 21 December 2016

Difference : List Vs Map

List and Map differ based on following parameters:

1.      Approch
List stores only the value of the element.
Map applies different mechanism as it stores value of the element along with a unique key associated to the each stored value.

2.      Memory requirement
As List only stores the value of the element so it requires less memory space in comparison to Map.
On other hand Map needs to store a unique key for each value so memory requirement increases.

3.      Implementation
ArrayList, LinkedList and Vector implements List interface.
HashMap, LinkedHashMap, TreeMap, etc. implements Map interface.

4.      Order maintainence
List ensures that the insertion order is maintained.
All Map implementations doesn’t guarantee of maintaining insertion order (if you care about order, useLinkedHashMap).
*In case where insertion order is maintained we get the elements returned in same order in which they were inserted while retrieving them.

5.      Null value
Any number of null values can be stored in List.
Only one null key is allowed in Map. But you can store any number of null values.

6.      Duplicate value
List accepts duplicate values while storing.
Map doesn’t accept duplicate Key. But duplicate values are allowed.

7.      Retrieve element
In List elements can be retrieved specifying index of the element.
In Map elements can be retrieved by specifying its Key.

8.      Example
List Example


package javaRadarArrayList;

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

public class SimpleArrayList {

      public static void main(String[] args) {
            //create Array List
            List<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);
      }
}

OUTPUT:

[Java, Spring, Hibernate, EJB]


Map Example

package map;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class MapExample {

        public static void main(String[] args) {

                        Map m = new HashMap<String, String>();
                        m.put("x", "1");
                        m.put("w", "2");
                       
                        Set set = m.entrySet();
                        Iterator itr = set.iterator();
                       
                        while(itr.hasNext()){
                                        Map.Entry entry = (Map.Entry) itr.next();
                                        System.out.println(entry.getKey() + " "+ entry.getValue());
                        }

        }

}

OUTPUT:
w 2
x 1



You may also like to read:

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
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.