downloadfile-2

Upload: sabari-nathan

Post on 04-Nov-2015

10 views

Category:

Documents


0 download

DESCRIPTION

java new

TRANSCRIPT

  • Core JavaJAVA Collection Framework :

    Collection Framework provides an architecture to store and manipulate the group of objects.

    All the operations that you perform on a data such as searching, sorting, insertion, deletion etc. can be performed by Java Collection Framework.

    Collection simply means a single unit of objects.

    Collection framework provides many interfaces (Set, List, Queue, Deque etc.) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet etc).

    What is Collection ?

    Collection represents a single unit of objects i.e. a group.

    What is framework ?

    provides ready-made architecture. represents set of classes and interface. is optional.

    Collection framework

    Collection framework represents a unified architecture for storing and manipulating group of object. It has:

    Interfaces and its implementations i.e. classes Algorithm

    Hierarchy of Collection Framework :

    Let us see the hierarchy of collection framework. The java.util package contains all the classes and interfaces for Collection framework.

    Interfaces are mentioned as Green color boxClasses are mentioned as purple color box

  • Core Java

    Iterator interface :

    Iterator interface provides the facility of iterating the elements in forward direction only.

    Methods of Iterator interface :

    public boolean hasNext() it returns true if iterator has more elements.

    public object next() it returns the element and moves the cursor pointer to the next element.

    public void remove() it removes the last elements returned by the iterator. It is rarely used.

    Advantages Of Collection Framework :

    Reduces programming effort by providing data structures and algorithms so you don't have to write them yourself.

    Increases performance by providing high-performance implementations of data structures and algorithms. Because the various implementations of each interface are interchangeable, programs can be tuned by switching implementations.

    Collection is resizable and can grow

  • Core Java

    List Of Interfaces and Classes :

    Interface Hash Table Resizable ArrayBalanced

    Tree Linked List Hash Table + Linked List

    Set HashSet TreeSet LinkedHashSetList ArrayList LinkedListDeque ArrayDeque LinkedListMap HashMap TreeMap LinkedHashMap

    Simple Collection Hierarchy :

    Disadvantages of Collection Framework :

    It must cast to correct type. It can't be done compile-time type checking.

    ArrayList :

    Uses a dynamic array for storing elements. It extends AbstractList and implements List

    can contain duplicate elements not synchronized maintains insertion order random access because array works at the index basis manipulation slow because a lot of shifting needs to be occurred ArrayList supports both Iterator and ListIterator for iteration It allows null values. It supports Generic which makes Java ArrayList even more powerful

    because of enhanced type-safety

  • Core Java

    ArrayList supports dynamic arrays that can grow as needed. Standard Java arrays are of a fixed length. After arrays are

    created, they cannot grow or shrink, which means that you must know in advance how many elements an array will hold.

    Array lists are created with an initial size. When this size is exceeded, the collection is automatically enlarged. When objects are removed, the array may be shrunk.

    The ArrayList class supports three constructors. The first constructor builds an empty array list.

    1. ArrayList( )

    The following constructor builds an array list that is initialized with the elements of the collection c.

    2. ArrayList(Collection c)

    The following constructor builds an array list that has the specified initial capacity. The capacity is the size of the underlying array that is used to store the elements.The capacity grows automatically as elements are added to an array list.

    3. ArrayList(int capacity)

    ArrayList is not a synchronized collection hence it is not suitable to be used between multiple threads concurrently. If you want to use ArrayList then you need to either use new CopyonWriteArrayList or use Collections.synchronizedList() to create a synchronized List.

  • Core JavaExample,List list = Collections.synchronizedList(new ArrayList(...));

    CopyOnWriteArrayList threadSafeList = new CopyOnWriteArrayList();threadSafeList.add("Java");threadSafeList.add("J2EE");threadSafeList.add("Collection");

    CopyonWriteArrayList is recommended for concurrent multi-threading environment as it is optimized for multiple concurrent read and creates copy for write operation.

    Example Of ArrayList :

    1) Creating ArrayList ArrayList stringList = new ArrayList(); //Generic ArrayList to Store only String objects

    2) Checking size of ArrayListSize of an ArrayList in Java is total number of elements currently stored in ArrayList.

    Int size = stringList.size();

    3) Checking Index of an Item in Java ArraylistYou can use indexOf() method of ArrayList in Java to find out index of a particular object.

    Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.

    Int index = stringList.indexOf("Item");//location of Item object in ListReturns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element.

    Int index = stringList.lastIndexOf("Item");//location of Item object in List

    4) Checking ArrayList for an Item

    Sometimes we need to check whether an element exists in ArrayList in Java or not for this purpose we can use contains() method of Java. contains() method takes type of object defined in ArrayList creation and returns true if this list contains the specified element.

  • Core Javacontains(Object o)Returns true if this list contains the specified element

    5) Removing an Item from ArrayList

    There are two ways to remove any elements from ArrayList in Java. You can either remove an element based on its index or by providing object itself.

    Remove remove (int index) and remove (Object o) method is used to remove any element from ArrayList in Java.

    Since ArrayList allows duplicate its worth noting that remove(Object o) removes the first occurrence of the specified element from this list, if it is present.

    In below code first call will remove first element from ArrayList while second call will remove first occurrence of item from ArrayList in Java.

    stringList.remove(0); Removes the element at the specified position in this list.stringList.remove(item); Removes the first occurrence of the specified element from this list, if it is present.

    6) Copying data from one ArrayList to another ArrayList in Java

    Many a times you need to create a copy of ArrayList for this purpose you can use addAll(Collection c) method of ArrayList in Java to copy all elements from on ArrayList to another ArrayList in Java.

    Below code will add all elements of stringList to newly created copyOfStringList.

    ArrayListcopyOfStringList =newArrayList();copyOfStringList.addAll(stringList);

    7) Replacing an element at a particular index

    You can use set (int index, E element) method of java ArrayList to replace any element from a particular index.

    stringList.set(0,"Item2");

    8) Converting from ArrayList to Array in Java

    Java ArrayList provides you facility to get the array back from your ArrayList.

  • Core Java

    You can use toArray(T[] a) method returns an array containing all of the elements in this list in proper sequence (from first to last element).

    String[]itemArray =newString[stringList.size()];String[]returnedArray = stringList.toArray(itemArray);

    9) Converting from Array to ArrayList in Java

    This is the simplest way of converting from array to arraylist.

    String[] asset = {"equity", "stocks", "gold", "foreign exchange","fixed income", "futures", "options"};List assetList =Arrays.asList(asset);

    Its worth to note following point while using Arrays.asList() method for array to arraylist conversion

    1) This method returns a List view of underlying array.2) List returned by this method would be fixed size.3) Most important point to note is when you change an element into this List corresponding element in original array will also be changed.4) Another important point is since List is fixed size, you can not add element into it. If you try you will get exception.5) This is the most efficient way of converting array to arraylist as per my knowledge because it doesn't copy the content of underlying array to create list.6) From Java 5 or JDK 1.5 onwards this method supports generic so you can generate type safe ArrayList from array.

    10) Array to ArrayList by using Collections.addAll method

    This example of converting an array to arraylist is not that efficient as the earlier method but its more flexible.

    List assetList = new ArrayList();String[] asset = {"equity", "stocks", "gold", "foriegn exchange", "fixed income", "futures", "options"};

    Collections.addAll(assetList, asset);

    Important point about this method of array to ArrayList conversion is :

    1) Its not as fast as Arrays.asList() but more flexible.2) This method actually copies the content of the underlying array into ArrayList provided.3) Since you are creating copy of original array, you can add, modify and remove any element without affecting original one.4) If you want to provide individual element you can do so by specifying

  • Core Javathem individually as comma separated. Which is a very convenient way of inserting some more elements into existing list for example,

    Collections.addAll(assetList,"EquityDerivatives","Eqity Index Arbitrage","Mutual Fund");

    11) This is another great way of converting an array to arraylist.

    We are essentially using Collection interface's addAll() method for copying content from one list to another.

    Since List returned by Arrays.asList is fixed-size its not much of use, this way we can convert that into proper arraylist.

    Arraylist newAssetList =newArraylist();newAssetList.addAll(Arrays.asList(asset));

    12) Creating Synchronized ArrayList

    Some times you need to synchronize your ArrayList in java to make it shareable between multiple threads you can use Collections utility class for this purpose as shown below.

    List list =Collections.synchronizedList(newArrayList(...)); (or)

    CopyOnWriteArrayList threadSafeList = new CopyOnWriteArrayList();threadSafeList.add("Java");threadSafeList.add("J2EE");threadSafeList.add("Collection");

    13) ArrayList to HashSet conversion Most of Collection class provides a constructor which accepts a

    Collection object as argument. Which can be used to copy all elements of one Collection into another.

    HashSet also provide such constructors which can be used to copy all object from ArrayList to HashSet. But be careful since HashSet doesn't allow duplicates some of the objects will not be included which result in less number of objects.

    Also List allows duplicates but Set doesn't allow any duplicates, which means if you have duplicates in your ArrayList they will be lost when you convert ArrayList to HashSet and that's the reason why sometime size of ArrayList doesn't match with size of HashSet after conversion

    Example,

    HashSet companySet = new HashSet(Collection

  • Core Java

    14) If we set ArrayList reference null in Java all the elements inside ArrayList becomes eligible to garbage collection in java , provided there are no more reference exists for those objects.

    Difference between Arrays and ArrayList :

    Arrays ArrayList

    Arrays are strongly typed. Hence only same type of elements can stored. (Ex. if A is an array, here we can store only integer or string or bool etc..)

    ArrayList are not strongly typed(Loosely typed).

    Since strongly typed, boxing and unboxing never happens. This result in better performance

    Since Loosely typed, boxing and unboxing happens which results in performance problem

    These are fixed in size and will not grow dynamically runtime

    They can grow dynamically while runtime

    To store and to retrieve we should use integral indexArray dont support Add() and Remove() functions

    ArrayList provide sufficient methods to work with like Add()

    ADVANTAGES OF USING ARRAYLIST

    An array is type specific i.e. one array can only store data of only one data type where as arraylist can store multiple data in the form of objects. So multiple objects of different data types can be stored in arraylist.

    In array you cannot increase or decrease the size dynamically where as in arraylist the size can be increased or decreased dynamically.

    You can make arraylist readonly. You can insert element at any location in arraylist. Arraylist supports BinarySearch. ArrayLists implement iterable , which means you can easily iterate

    them. If an arraylist is modified by another thread while it is being

    iterated by one thread , then it fails fast , which means you don't end up with unreliable data in the list.

  • Core Java

    DISADVANTAGES OF USING ARRAYLIST

    Not efficient for large quantity of data because when the arraylist has to increase its size, its content is copied to a larger arraylist which can be a slow process.

    It can only holds Objects i.e. it cant hold normal data types values such as int .

    Make ArrayList as ReadOnly :Example,Syntax :

    public static List unmodifiableList(List

  • Core Javathread-safe. Now, What does that mean? It means if multiple thread try to access Vector same time they can do that without compromising Vector's internal state. Same is not true in case of ArrayList as methods like add(), remove() or get() is not synchronized.

    2) Second major difference on Vector vs ArrayList is Speed, which is directly related to previous difference. Since Vector is synchronized, its slow and ArrayList is not synchronized its faster than Vector.

    3) Third difference on Vector vs ArrayList is that Vector is a legacy class and initially it was not part of Java Collection Framework.

    These were some comparison on Vector vs ArrayList. In Summary use ArrayList if you are using ArrayList in Single threaded environment and use Vector if you need a thread-safe collection. ArrayList is anytime faster than Vector in case thread-safety is not a concern.

    What do you mean by Legacy class in JAVA?

    Legacy classes are those that were built using Java 1.1 or Java 1.2 API. In general we cannot use this term for java classes. Say for example when Java 1.0 was available Vector was used instead of dynamic array and since there was no ArrayList class people were forced to use Vector for this purpose.

    When Java 1.2 was released ArrayList was much more advanced to Vector but has all the features of Vector too. So people started using ArrayList instead of Vector (this again depends on the project requirement, both Vector and ArrayList have their own advantages). And in this case Vector became legacy class.

    But this is not constant since in future Sun may introduce a new class that is much more advanced to ArrayList and Vector. And then we call both ArrayList and Vector as legacy classes.

    But in general a "legacy" is a term used to define a software created using older version of software.

    Example,public static void main(String[] args) {

    List list = new ArrayList(); list.add("Text 1"); list.add("Text 2"); list.add("Text 3"); System.out.println("#1 normal for loop"); for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); }

  • Core Java System.out.println("#2 advance for loop"); for (String temp : list) { System.out.println(temp); } System.out.println("#3 while loop"); int j = 0; while (list.size() > j) { System.out.println(list.get(j)); j++; } System.out.println("#4 iterator"); Iterator iterator = list.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } }

    What is Mutable and Immutable Objects in Java ?

    An immutable object is an object whose state cannot be modified after it is created.

    This is in contrast to a mutable object, which can be modified after it is created

    Example ,int i = 42; //int is of primitive type Mutablei = 43; // OK final int j = 42; Immutablej = 43; // does not compile. j is final so can't be reassigned

    In Java, objects are referred by references. If an object is known to be immutable, the object reference can be shared. For example, Boolean, Byte, Character, Double, Float, Integer, Long, Short, and String are immutable classes in Java, but the class StringBuffer is a mutable object in addition to the immutable String.class Program { public static void main(String[] args) { String str = "HELLO"; System.out.println(str); str.toLowerCase(); System.out.println(str); }}The output result isHELLOHELLO

    From the above example, the toLowerCase() method does not impact on the

  • Core Javaoriginal content in str. What happens is that a new String object "hello" is constructed. The toLowerCase() method returns the new constructed String object's reference. Let's modify the above code:

    class Program { public static void main(String[] args) { String str = "HELLO"; System.out.println(str); String str1 = str.toLowerCase(); System.out.println(str1); }}The output result isHELLOhello

    The str1 references a new String object that contains "hello". The String object's method never affects the data the String object contains, excluding the constructor.

    Difference between String and StringBuffer/StringBuilder in JavaWell, the most important difference between String and StringBuffer/StringBuilder

    in java is that String object is immutable whereas StringBuffer /

    StringBuilder objects are mutable.

    By immutable, we mean that the value stored in the String object cannot be changed. Then the next question that comes to our mind is If String is immutable then how am I able to change the contents of the object whenever I wish to? . Well, to be precise its not the same String object that reflects the changes you do. Internally a new String object is created to do the changes.

    So suppose you declare a String object:

    String myString = Hello;

    Next, you want to append Guest to the same String. What do you do?

    myString = myString + Guest;

    When you print the contents of myString the output will be Hello Guest. Although

    we made use of the same object(myString), internally a new object was

    created in the process. So, if you were to do some string operation involving an

  • Core Java

    append or trim or some other method call to modify your string object, you would

    really be creating those many new objects of class String.

    Now isnt that a performance issue?

    Yes, it definitely is.

    Then how do you make your string operations efficient?

    By using StringBuffer or StringBuilder.

    How would that help?

    Well, since StringBuffer/StringBuilder objects are mutable, we can make

    changes to the value stored in the object. What this effectively means is that string

    operations such as append would be more efficient if performed using

    StringBuffer/StringBuilder objects than String objects.

    Finally, whats the difference between StringBuffer and StringBuilder?

    StringBuffer and StringBuilder have the same methods with one difference and

    thats of synchronization. StringBuffer is synchronized( which means it is

    thread safe and hence you can use it when you implement threads for your

    methods) whereas StringBuilder is not synchronized( which implies it isnt

    thread safe).

    So, if you arent going to use threading then use the StringBuilder class

    as itll be more efficient than StringBuffer due to the absence of

    synchronization.

    Heres how you use StringBuilderNow get out of that bad habit of using String objects to perform operations on

    strings. With StringBuilder(introduced in J2Se 5.0), you can perform those very

    append and other such operations more efficiently.

    Scene 1: typical coder. using the same old String object to perform append

    operations.

  • Core Java

    String s = Hello;

    s = s + World;

    system.out.println(s);

    I agree itll give you Hello World, but fella. lets be different from the rest and

    think about making the code more efficient.

    Enter Scene 2.

    StringBuilder sb = new StringBuilder(Hello);

    sb.append( World);

    system.out.println(sb);

    well thats it!! Youll get your Hello World but in a more efficient way

    Simple example to demonstrate that String object is immutableIn my post Difference between String and StringBuffer/StringBuilder I told you stuff like String object is immutable( meaning the value stored in the object cannot

    be changed) and that when you perform operations such as concat or replace,

    internally a new object is created to hold the result.

    Below is a simple example that will make you believe that what I said about String

    object is indeed true!

    String s = Lets test;

    s.concat( if the String object is IMMUTABLE);

  • Core Java

    System.out.println(s);

    s = s.concat( if the String object is IMMUTABLE);

    System.out.println(s);

    The output of the above code will be:

    Lets test

    Lets test if the String object is IMMUTABLE

    Thats all people! The above piece of code proves that String is immutable and

    hence the results of operations like concat etc. should be stored into a new object.

    LinkedList :

    uses doubly linked list to store the elements. It extends the AbstractList class and implements List and Deque interfaces.

    Contain duplicate elements. maintains insertion order. Multiple Null values allowed here not synchronized. No random access. manipulation fast because no shifting needs to be occur. can be used as list, stack or queue.

    Example,public static void main(String[] args) { System.out.println("Linked List Example!"); LinkedList list = new LinkedList(); int num1 = 11, num2 = 22, num3 = 33, num4 = 44; int size; Iterator iterator; //Adding data in the list list.add(num1); list.add(num2); list.add(num3);

  • Core Java list.add(num4);

    size = list.size(); System.out.print( "Linked list data: "); //Create a iterator iterator = list.iterator(); while (iterator.hasNext()){ System.out.print(iterator.next()+" "); } System.out.println(); //Check list empty or not if (list.isEmpty()){ System.out.println("Linked list is empty"); } else{ System.out.println( "Linked list size: " + size); } System.out.println("Adding data at 1st location: 55"); //Adding first list.addFirst(55); System.out.print("Now the list contain: "); iterator = list.iterator(); while (iterator.hasNext()){ System.out.print(iterator.next()+" "); } System.out.println(); System.out.println("Now the size of list: " + list.size()); System.out.println("Adding data at last location: 66"); //Adding last or append list.addLast(66); System.out.print("Now the list contain: "); iterator = list.iterator(); while (iterator.hasNext()){ System.out.print(iterator.next()+" "); } System.out.println(); System.out.println("Now the size of list: " + list.size()); System.out.println("Adding data at 3rd location: 55"); //Adding data at 3rd position list.add(2,99); System.out.print("Now the list contain: ");

  • Core Java iterator = list.iterator(); while (iterator.hasNext()){ System.out.print(iterator.next()+" "); } System.out.println(); System.out.println("Now the size of list: " + list.size()); //Retrieve first data System.out.println("First data: " + list.getFirst()); //Retrieve lst data System.out.println("Last data: " + list.getLast()); //Retrieve specific data System.out.println("Data at 4th position: " + list.get(3)); //Remove first int first = list.removeFirst(); System.out.println("Data removed from 1st location: " + first); System.out.print("Now the list contain: "); iterator = list.iterator(); //After removing data while (iterator.hasNext()){ System.out.print(iterator.next()+" "); } System.out.println(); System.out.println("Now the size of list: " + list.size()); //Remove last int last = list.removeLast(); System.out.println("Data removed from last location: " + last); System.out.print("Now the list contain: "); iterator = list.iterator(); //After removing data while (iterator.hasNext()){ System.out.print(iterator.next()+" "); } System.out.println(); System.out.println("Now the size of list: " + list.size()); //Remove 2nd data int second = list.remove(1); System.out.println("Data removed from 2nd location: " + second); System.out.print("Now the list contain: "); iterator = list.iterator(); //After removing data

  • Core Java while (iterator.hasNext()){ System.out.print(iterator.next()+" "); } System.out.println(); System.out.println("Now the size of list: " + list.size()); //Remove all list.clear(); if (list.isEmpty()){ System.out.println("Linked list is empty"); } else{ System.out.println( "Linked list size: " + size); } }public class LinkedListTest {

    public static void main(String[] args) {

    List ll = new LinkedList();ll.add("3");ll.add("2");ll.add(null);ll.add("4");ll.add("4");ll.add(null);ll.add(null);ll.add(null);

    Iterator iter2 = ll.iterator();while(iter2.hasNext()){

    System.out.println(iter2.next());}

    }}

    Output :32null44nullnullnull

  • Core JavaDoubly Linked List :

    A doubly-linked list is a linked data structure that consists of a set of sequentially linked records called nodes.

    Each node contains two fields, called links, that are references to the previous and to the next node in the sequence of nodes.

    The beginning and ending nodes' previous and next links, respectively, point to some kind of terminator, typically a sentinel node or null, to facilitate traversal of the list.

    If there is only one sentinel node, then the list is circularly linked via the sentinel node. It can be conceptualized as two singly linked lists formed from the same data items, but in opposite sequential orders

    ArrayList vs LinkedList vs Vector :

    List, as its name indicates, is an ordered sequence of elements.

    When we talk about List, it is a good idea to compare it with Set which is a set of elements which is unordered and every element is unique. The following is the class hierarchy diagram of Collection.

  • Core JavaArrayList vs. LinkedList vs. Vector

    From the hierarchy diagram, they all implement List interface. They are very similar to use. Their main difference is their

    implementation which causes different performance for different operations. ArrayList is implemented as a resizable array. As more elements are

    added to ArrayList, its size is increased dynamically. It's elements can be accessed directly by using the get and set methods, since ArrayList is essentially an array.

    LinkedList is implemented as a double linked list. Its performance on add and remove is better than Arraylist, but worse on get and set methods.

    Vector is similar with ArrayList, but it is synchronized. ArrayList is a better choice if your program is thread-safe. Vector and ArrayList require space as more elements are added.

    Vector each time doubles its array size, while ArrayList grow 50% of its size each time.

    LinkedList, however, also implements DeQue interface which adds more methods than ArrayList and Vector, such as offer(), peek(), poll(), etc.

    Note: The default initial capacity of an ArrayList is pretty small. It is a good habit to construct the ArrayList with a higher initial capacity. This can avoid the resizing cost.

    Time Duration :

    ArrayList add: 13265642LinkedList add: 9550057ArrayList get: 1543352LinkedList get: 85085551ArrayList remove: 199961301LinkedList remove: 85768810

    The difference of their performance is obvious. LinkedList is faster in add and remove, but slower in get. LinkedList should be preferred if:

    There are no large number of random access of element GET There are a large number of add/remove operations Add/Remove

  • Core JavaList Interface :

    List Interface is the subinterface of Collection. It contains methods to insert and delete elements in index basis. It is a factory of ListIterator interface.

    public void add(int index,Object element); public boolean addAll(int index,Collection c); public object get(int Index position); public object set(int index,Object element); public object remove(int index); public ListIterator listIterator(); public ListIterator listIterator(int i);

    ListIterator :

    ListIterator Interface is used to traverse the element in backward and forward direction

    public boolean hasNext(); public Object next(); public boolean hasPrevious(); public Object previous();

    Difference between List & ListIterator :

    There are two Differences :1) We can use Iterator to traverse Set and List and also Map type of Objects. But List Iterator can be used to traverse for List type Objects, but not for Set type of Objects.That is, we can get a Iterator object by using Set and List, see here :By using Iterator we can retrieve the elements from Collection Object in forward direction only.

    Methods in Iterator :

    1.hashNext()2.next()3.remove()

    Iterator ite = Set.iterator(); Iterator ite = List.iterator();

  • Core Java

    2) But we get List Iterator object only from List interface, see here :where as List Iterator, which allows you to traverse in either directions. That is List Iterators traverse two directions. So it has another methods hasPrevious() & previous() other than Iterator.Methods in ListIterator

    1.hasNext()2.next()3.previous() 4.hasPrevious()5.remove()6.nextIndex()7.previousIndex()

    ListIterator listite = List.listIterator();

    i.e., we can't get List Iterator object from Set interface.

    Sno Iterator List Iterator1 Using iterator you can visit

    the elements of collection in the forward direction only

    In list iterator you can visit the elements of collection in the forward and backward direction.

    2 Using iterator you cannot add elements to collection

    Using list Iterator you can add elements to collection

    3 Using iterator you can not replace existing object with new object

    Using iterator you can replace existing object with new object

    4 Using iterator you can not get index of elements

    Using list Iterator you can get index of elements list

    5 Methods in Iterator :

    hashNext() next() remove()

    Methods in ListIterator

    hasNext()next()previous() hasPrevious()remove()nextIndex()previousIndex()

    6 Iterator to traverse Set and List and also Map type of Objects

    List Iterator can be used to traverse for List type Objects

    7 Here cursor position always points to a specific index

    Here cursor lies between the element that will be returned by call to previous() and element that will be returned by call to next()

  • Core Java

    Example,public class IteratorAndListIterator {

    public static void main(String[] args) {List namesList = new ArrayList();namesList.add("A");namesList.add("B");namesList.add("C");namesList.add("D");namesList.add("E");

    Iterator iterator = namesList.iterator();

    System.out.println("Using Iterator");while (iterator.hasNext()) {

    System.out.println(iterator.next());}

    System.out.println();System.out.println("Using List Iterator");ListIterator listIterator = namesList.listIterator();while (listIterator.hasNext()) {

    System.out.print(listIterator.nextIndex());System.out.println(" " + listIterator.next());

    }

    System.out.println();System.out.println("Using ListIterator with Insertion of an

    element");listIterator = namesList.listIterator();while (listIterator.hasNext()) {

    System.out.print(listIterator.nextIndex());if (listIterator.nextIndex() == 2) {

    listIterator.add("Q");}System.out.println(" " + listIterator.next());

    }

    System.out.println();System.out.println("Using ListIterator with iteration in

    reverse order");listIterator = namesList.listIterator(6);while (listIterator.hasPrevious()) {

    System.out.print(listIterator.previousIndex());System.out.println(" " + listIterator.previous());

    }}

    }

  • Core JavaOutput

    Using IteratorABCDE Using List Iterator0 A1 B2 C3 D4 E Using ListIterator with Insertion of an element0 A1 B2 C4 D5 E Using ListIterator with iteration in reverse order5 E4 D3 C2 Q1 B0 A

    Difference between List and Set :

    List Set

    Is an Ordered grouping of elements Is an Unordered grouping of elementsList is used to collection of elements with duplicates

    Set is used to collection of elements without duplicates

    Can be accessed by index Can not be accessed by indexLinkedListArrayList

    HashSet (unordered)LinkedHashSet (ordered)TreeSet (sorted by natural order or by provided comparator)

    SET :

    At most Allows one null element Does not allow duplicate elements Unordered grouping of elements

  • Core Java Can not be accessed by index basis Extends AbstractSet class implements Set interface

    HashSet :

    Uses hashtable to store the elements. It extends AbstractSet class and implements Set interface.

    Contains unique elements only. A HashSet is an unsorted, unordered Set

    HashSet is not synchronized. If more than one thread wants to access it at the same time then it must be synchronized externally.

    Example,class Simple{ public static void main(String args[]){ HashSet al=new HashSet(); al.add("Ravi"); al.add("Vijay"); al.add("Ravi"); al.add("Ajay"); Iterator itr=al.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } }}Output : Ajay Vijay RaviThe HashSet class supports four constructors. The first form constructs a default hash set:

    1) HashSet( )

  • Core JavaThe following constructor form initializes the hash set by using the elements of c.

    2) HashSet(Collection c)

    The following constructor form initializes the capacity of the hash set to capacity.The capacity grows automatically as elements are added to the Hash.

    3) HashSet(int capacity)

    The fourth form initializes both the capacity and the fill ratio (also called load capacity) of the hash set from its arguments:

    4) HashSet(int capacity, float fillRatio)

    Make it Synchronized Set :

    Set s = Collections.synchronizedSet(new HashSet()); ... synchronized (s) { Iterator i = s.iterator(); // Must be in the synchronized block while (i.hasNext()) foo(i.next()); }

    Make it Read-Only Colelction :

    Syntax :public static Set unmodifiableSet(Set

  • Core Java

    for (String str : linkedSet) {System.out.println(str);

    }*/

    for (String str : set) {System.out.println(str);

    }}

    Output : (default ascending order)ABCO

    Using LinkedHashset it displays insertion order likeOCAB

    public static void main(String [] args) { System.out.println( "Collection Example!\n" ); int size; // Create a collection HashSet set = new HashSet (); String str1 = "Yellow", str2 = "White", str3 = "Green", str4 = "Blue"; Iterator iterator; //Adding data in the collection set.add(str1); set.add(str2); set.add(str3); set.add(str4); System.out.print(" set data: "); //Create a iterator iterator = set.iterator(); while (iterator.hasNext()){ System.out.print(iterator.next() + " "); } System.out.println(); // Get size of a collection size = set.size(); if (set.isEmpty()){ System.out.println(" set is empty"); } else{ System.out.println( " set size: " + size);

  • Core Java } System.out.println(); // Remove specific data set.remove(str2); System.out.println("After removing [" + str2 + "]\n"); System.out.print("Now collection data: "); iterator = set.iterator(); while (iterator.hasNext()){ System.out.print(iterator.next() + " "); } System.out.println(); size = set.size(); System.out.println(" set size: " + size + "\n"); //Collection empty set.clear(); size = set.size(); if (set.isEmpty()){ System.out.println(" set is empty"); } else{ System.out.println( " set size: " + size); } }Readonly collections

    public class ReadOnlyCollections {

    public static void main(String args[]) {

    // creating a list

    List godList = Arrays

    .asList(new String[] { "Donald", "Dennis", "Ken" });

    // making a read-only list

    List list = new ArrayList(godList);

    list = Collections.unmodifiableList(list);

    // checking the reference in a read-only set

    Set set = new HashSet(godList);

    Collections.unmodifiableSet(set);

  • Core Java

    // the following statement allows to modify the above set as the

    // reference is pointing to the original collection therefore it is not

    // read-only

    set.add("Alan");

    // making a read-only map and try to modify it

    Map godMap = new HashMap();

    godMap.put("TAOCP", "Donald");

    godMap.put("C", "Dennis");

    godMap = Collections.unmodifiableMap(godMap);

    try {

    // modifying the read-only map to check what happens

    godMap.put("Unix", "Ken");

    } catch (UnsupportedOperationException e) {

    System.out.println("You cannot modify a read only collection!");

    }

    }

    }

    LinkedHashSet :

    Contains unique elements only like HashSet.

  • Core Java

    It extends HashSet class and implements Set interface. Maintains insertion order. A LinkedHashSet is an ordered version of HashSet that maintains a

    doubly-linked List across all elements. Use this class instead of HashSet when you care about the iteration

    order. When you iterate through a HashSet the order is unpredictable,

    while a LinkedHashSet lets you iterate through the elements in the order in which they were inserted.

    HashSet vs LinkedHashSet :

    The only difference is that the LinkedHashSet maintains the order of the items added to the Set.

    It does this by maintaining a doubly linked list containing the hash and the original order of the items.

    According to Sun, the LinkedHashSet should run nearly as fast as the HashSet.

    TreeSet :

    Contains unique elements only like HashSet. The TreeSet class implements NavigableSet interface that extends the

    SortedSet interface Maintains ascending order. It extends AbstractSet class A NavigableSet implementation based on a

    TreeMap. The elements are ordered using their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used.

    Its not synchronized. To make it as synchronized set do the following,

    SortedSet s = Collections.synchronizedSortedSet(new TreeSet(...));

  • Core JavaExample,

    public static void main(String[] args) { System.out.println("Tree Set Example!\n"); TreeSet tree = new TreeSet(); tree.add(12); tree.add(63); // Output 12, 34, 45, 63 tree.add(34); tree.add(45); // here it test it's sorted, 63 is the last element. see output below Iterator iterator = tree.iterator(); System.out.print("Tree set data: "); //Displaying the Tree set data while (iterator.hasNext()) { System.out.print(iterator.next() + " "); } System.out.println(); //Check empty or not if (tree.isEmpty()) { System.out.print("Tree Set is empty."); } else { System.out.println("Tree Set size: " + tree.size()); } //Retrieve first data from tree set System.out.println("First data: " + tree.first()); //Retrieve last data from tree set System.out.println("Last data: " + tree.last()); if (tree.remove(45)) { // remove element by value System.out.println("Data is removed from tree set"); } else { System.out.println("Data doesn't exist!"); } System.out.print("Now the tree set contain: "); iterator = tree.iterator(); //Displaying the Tree set data while (iterator.hasNext()) { System.out.print(iterator.next() + " "); } System.out.println(); System.out.println("Now the size of tree set: " + tree.size()); //Remove all tree.clear(); if (tree.isEmpty()) { System.out.print("Tree Set is empty."); } else { System.out.println("Tree Set size: " + tree.size()); } }

  • Core JavaHashSet vs TreeSet vs LinkedHashSet :

    In a set, there are no duplicate elements. That is one of the major reasons to use a set.

    There are 3 commonly used implementations of Set in Java: 1) HashSet,2) TreeSet and3) LinkedHashSet.When and which to use is an important question.

    In brief, if we want a fast set, we should use HashSet; if we need a sorted set, then TreeSet should be used; if we want a set that can be read by following its insertion order,

    LinkedHashSet should be used. HashSet is Implemented using a hash table. Elements are not ordered.

    The add, remove, and contains methods has constant time complexity O(1).

    TreeSet is implemented using a tree structure(red-black tree in algorithm book). The elements in a set are sorted, but the add, remove, and contains methods has time complexity of O(log (n)). It offers several methods to deal with the ordered set like first(), last(), headSet(), tailSet(), etc.

    LinkedHashSet is between HashSet and TreeSet. It is implemented as a hash table with a linked list running through it, so it provides the order of insertion. The time complexity of basic methods is O(1).

    What is common in HashSet and TreeSet in Java .?

    1)Both HashSet and TreeSet implements java.util.Set interface which means they follow contract of Set interface and doesn't allow any duplicates.

    2)Both HashSet and TreeSet are not thread-safe and not synchronized. Though you can make them synchronized by using Collections.synchronizedSet() method.

    3) Third similarity between TreeSet and HashSet is that, Iterator of both classes are fail-fast in nature. They will throw ConcurrentModificationException if Iterator is modified once Iterator is created. this is not guaranteed and application code should not rely on this code but Java makes best effort to fail as soon as it detects structural change in underlying Set.

  • Core JavaHashSet vs TreeSet in JavaNow let's see couple of differences between HashSet vs TreeSet in Java. This is enough to decide whether you should use HashSet or TreeSet in a given scenario.

    1) First major difference between HashSet and TreeSet is performance. HashSet is faster than TreeSet and should be preferred choice if sorting of element is not required.

    2) Second difference between HashSet and TreeSet is that HashSet allows null object but TreeSet doesn't allow null Object and throw NullPointerException, Why, because TreeSet uses compareTo() method to compare keys and compareTo() will throw java.lang.NullPointerException as shown in below example :

    HashSet hashSet =new HashSet();hashSet.add("Java");hashSet.add(null); TreeSet treeSet =new TreeSet();treeSet.add("C++");treeSet.add(null);//Java.lang.NullPointerExceptionOutput:Exceptionin thread"main"java.lang.NullPointerException at java.util.TreeMap.put(TreeMap.java:541) at java.util.TreeSet.add(TreeSet.java:238) at test.CollectionTest.main(CollectionTest.java:27)JavaResult:1

    3) Another significant difference between HashSet and TreeSet is that , HashSet is backed by HashMap while TreeSet is backed by TreeMap in Java.

    4) One more difference between HashSet and TreeSet which is worth remembering is that HashSet uses equals() method to compare two object in Set and for detecting duplicates while TreeSet uses compareTo() method for same purpose. If equals() and compareTo() are not consistent, i.e. for two equal object equals should return true while compareTo() should return zero, than it will break contract of Set interface and will allow duplicates in Set implementations like TreeSet

    5) Now most important difference between HashSet and TreeSet is ordering. HashSet doesn't guaranteed any order while TreeSet maintains objects in Sorted order defined by either Comparable or Comparator method in Java.

  • Core JavaComparable Interface : (for sorting purpose)

    Comparable interface is used to order the objects of user-defined class.

    This interface is found in java.lang package and contains only one method named compareTo(Object).

    It provide only single sorting sequence i.e. you can sort the elements based on single data member only.

    public int compareTo(Object obj) is used to compare the current object with the specified object.

    Collections class provides static methods for sorting the elements of collection.

    If collection elements are of Set type, we can use TreeSet. But We cannot sort the elements of List.

    Collections class provides methods for sorting the elements of List type elements.

    public void sort(List list) is used to sort the elements of List. List elements must be of Comparable type.

    Note: String class and Wrapper classes implements the Comparable interface. So if you store the objects of string or wrapper classes, it will be Comparable.

    If any class implements comparable interface then collection of that object can be sorted automatically using Collection.sort() or Arrays.sort(). Object will be sort on the basis of compareTo method in that class.

    Example ,class Student implements Comparable{int rollno;String name;int age;Student(int rollno,String name,int age){this.rollno=rollno;this.name=name;this.age=age;}

  • Core Javapublic int compareTo(Object obj){Student st=(Student)obj;if(age==st.age)return 0;else if(age > st.age)return 1;elsereturn -1;}}

    Comparator interface :

    Comparator interface is used to order the objects of user-defined class.

    This interface is found in java.util package and contains only one method named compare(Object obj1,Object obj2).

    It provides multiple sorting sequence i.e. you can sort the elements based on any data member.

    public int compare(Object obj1,Object obj2) compares the first object with second object.

    Example,1) class AgeComparator implements Comparator{public int Compare(Object o1,Object o2){Student s1=(Student)o1;Student s2=(Student)o2;

    if(s1.age==s2.age)return 0;else if(s1.age>s2.age)return 1;elsereturn -1;}}

  • Core Java2) class NameComparator implements Comparator{public int Compare(Object o1,Object o2){Student s1=(Student)o1;Student s2=(Student)o2;

    return s1.name.compareTo(s2.name);}}3) class Simple{public static void main(String args[]){ArrayList al=new ArrayList();al.add(new Student(101,"Vijay",23));al.add(new Student(106,"Ajay",27));al.add(new Student(105,"Jai",21));System.out.println("Sorting by Name...");Collections.sort(al,new NameComparator());

    Iterator itr=al.iterator();while(itr.hasNext()){Student st=(Student)itr.next();System.out.println(st.rollno+" "+st.name+" "+st.age);}System.out.println("sorting by age...");Collections.sort(al,new AgeComparator());

    Iterator itr2=al.iterator();while(itr2.hasNext()){Student st=(Student)itr2.next();System.out.println(st.rollno+" "+st.name+" "+st.age);}}}

  • Core JavaComparator vs Comparable :

    Parameter Comparable Comparator

    Sorting logic

    Sorting logic must be in same class whose objects are being sorted. Hence this is called natural ordering of objects

    Sorting logic is in separate class. Hence we can write different sorting based on different attributes of objects to be sorted. E.g. Sorting using id, name etc.

    Implementation

    Class whose objects to be sorted must implement this interface. e.g Country class needs to implement comparable to collection of country object by id

    Class whose objects to be sorted do not need to implement this interface. Some other class can implement this interface. E.g.-CountrySortByIdComparator class can implement Comparator interface to sort collection of country object by id

    Sorting method

    int compareTo(Object o1)This method compares this object with o1 object and returns a integer. Its value has following meaning1. positive this object is greater than o12. zero this object equals to o13. negative this object is less than o1

    int compare(Object o1,Object o2)This method compares o1 and o2 objects. and returns a integer. Its value has following meaning.1. positive o1 is greater than o22. zero o1 equals to o23. negative o1 is less than o1

    Calling methodCollections.sort(List)Here objects will be sorted on the basis of CompareTo method

    Collections.sort(List, Comparator)Here objects will be sorted on the basis of Compare method in Comparator

    Package Java.lang.Comparable Java.util.ComparatorSorting Sequence

    Accepts Single Sorting Sequence Accepts Multiple Sorting Sequence

    Example,package org.arpit.javapostsforlearning;//If this.cuntryId < country.countryId:then compare method will return -1//If this.countryId > country.countryId:then compare method will return 1//If this.countryId==country.countryId:then compare method will return 0public class Country implements Comparable{ int countryId; String countryName;

    public Country(int countryId, String countryName) { super(); this.countryId = countryId; this.countryName = countryName; }

    @Override

  • Core Java public int compareTo(Object arg0) { Country country=(Country) arg0; return (this.countryId < country.countryId ) ? -1: (this.countryId > country.countryId ) ? 1:0 ; } public int getCountryId() { return countryId; }

    public void setCountryId(int countryId) { this.countryId = countryId; }

    public String getCountryName() { return countryName; }

    public void setCountryName(String countryName) { this.countryName = countryName; }

    }

    ComparableMain :package org.arpit.javapostsforlearning;

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

    public class ComparableMain {

    /** * @author Arpit Mandliya */ public static void main(String[] args) { Country indiaCountry=new Country(1, 'India'); Country chinaCountry=new Country(4, 'China'); Country nepalCountry=new Country(3, 'Nepal'); Country bhutanCountry=new Country(2, 'Bhutan');

    List listOfCountries = new ArrayList(); listOfCountries.add(indiaCountry); listOfCountries.add(chinaCountry); listOfCountries.add(nepalCountry); listOfCountries.add(bhutanCountry);

    System.out.println('Before Sort : '); for (int i = 0; i < listOfCountries.size(); i++) { Country country=(Country) listOfCountries.get(i); System.out.println('Country Id: '+country.getCountryId()+'||'+'Country name: '+country.getCountryName()); } Collections.sort(listOfCountries);

  • Core Java

    System.out.println('After Sort : '); for (int i = 0; i < listOfCountries.size(); i++) { Country country=(Country) listOfCountries.get(i); System.out.println('Country Id: '+country.getCountryId()+'|| '+'Country name: '+country.getCountryName()); } }

    }

    Before Sort : Country Id: 1||Country name: IndiaCountry Id: 4||Country name: ChinaCountry Id: 3||Country name: NepalCountry Id: 2||Country name: BhutanAfter Sort : Country Id: 1|| Country name: IndiaCountry Id: 2|| Country name: BhutanCountry Id: 3|| Country name: NepalCountry Id: 4|| Country name: China

    Comparator Example,package org.arpit.javapostsforlearning;

    public class Country{ int countryId; String countryName;

    public Country(int countryId, String countryName) { super(); this.countryId = countryId; this.countryName = countryName; }

    public int getCountryId() { return countryId; }

    public void setCountryId(int countryId) { this.countryId = countryId; }

    public String getCountryName() { return countryName; }

    public void setCountryName(String countryName) { this.countryName = countryName; }

    }

  • Core Javapackage org.arpit.javapostsforlearning;

    import java.util.Comparator;//If country1.getCountryId()country2.getCountryId():then compare method will return 1//If country1.getCountryId()==country2.getCountryId():then compare method will return 0 public class CountrySortByIdComparator implements Comparator{ @Override public int compare(Country country1, Country country2) { return (country1.getCountryId() < country2.getCountryId() ) ? -1: (country1.getCountryId() > country2.getCountryId() ) ? 1:0 ; }}

    package org.arpit.javapostsforlearning;

    import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.List;

    public class ComparatorMain {

    /** * @author Arpit Mandliya */ public static void main(String[] args) { Country indiaCountry=new Country(1, 'India'); Country chinaCountry=new Country(4, 'China'); Country nepalCountry=new Country(3, 'Nepal'); Country bhutanCountry=new Country(2, 'Bhutan');

    List listOfCountries = new ArrayList(); listOfCountries.add(indiaCountry); listOfCountries.add(chinaCountry); listOfCountries.add(nepalCountry); listOfCountries.add(bhutanCountry);

    System.out.println('Before Sort by id : '); for (int i = 0; i < listOfCountries.size(); i++) { Country country=(Country) listOfCountries.get(i); System.out.println('Country Id: '+country.getCountryId()+'||'+'Country name: '+country.getCountryName()); } Collections.sort(listOfCountries,new CountrySortByIdComparator()); System.out.println('After Sort by id: '); for (int i = 0; i < listOfCountries.size(); i++) {

  • Core Java Country country=(Country) listOfCountries.get(i); System.out.println('Country Id: '+country.getCountryId()+'|| '+'Country name: '+country.getCountryName()); }

    //Sort by countryName Collections.sort(listOfCountries,new Comparator() { @Override public int compare(Country o1, Country o2) { return o1.getCountryName().compareTo(o2.getCountryName()); } });

    System.out.println('After Sort by name: '); for (int i = 0; i < listOfCountries.size(); i++) { Country country=(Country) listOfCountries.get(i); System.out.println('Country Id: '+country.getCountryId()+'|| '+'Country name: '+country.getCountryName()); } }

    }

    Before Sort by id : Country Id: 1||Country name: IndiaCountry Id: 4||Country name: ChinaCountry Id: 3||Country name: NepalCountry Id: 2||Country name: BhutanAfter Sort by id: Country Id: 1|| Country name: IndiaCountry Id: 2|| Country name: BhutanCountry Id: 3|| Country name: NepalCountry Id: 4|| Country name: ChinaAfter Sort by name: Country Id: 2|| Country name: BhutanCountry Id: 4|| Country name: ChinaCountry Id: 1|| Country name: IndiaCountry Id: 3|| Country name: Nepal

  • Core JavaMap :

    A map contains values based on the key i.e. key and value pair. Each pair is known as an entry. Map contains only unique elements. The Map interface is not an extension of Collection interface. Instead the interface starts of its own interface hierarchy, for

    maintaining key-value associations. The interface describes a mapping from keys to values, without

    duplicate keys The Map interface provides three (3) collection views, which allow a

    map's contents to be viewed as a set of keys, collection of values, or set of key-value mappings. keySet set of keys values collection of values entrySet set of key-value mappings

    Three general-purpose Map implementations: HashMap, TreeMap, and LinkedHashMap.

    Methods :1. public Object put(object key,Object value)2. public void putAll(Map map)3. public Object remove(object key)4. public Object get(Object key)5. public boolean containsKey(Object key)6. public boolean containsValue(Object value)7. public Set keySet()8. public Set entrySet()

    Entry :

    Entry is the subinterface of Map. So we will access it by Map.Entry name. It provides methods to get key and value.

    Methods :1. public Object getKey()2. public Object getValue()

  • Core JavaWhy use Map.Entry .?

    If you just need keys, use keySet(). If you just need values, use values(). If you're going to use keys and values in your subsequent code, then you're best off using entrySet().

    I frequently see people do this without entrySet(), and it usually looks something like this:

    1.for (Iterator it = map.keySet().iterator(); it.hasNext(); ) { 2. Foo key = (Foo) it.next(); 3. Bar value = (Bar) map.get(key); 4. // now do something with key and value 5.}

    This works, but it's making the JVM do extra work for no good reason. Every time you call get() you're making the JVM spend time doing a hashcode lookup, or navigating a tree and evaluating a comparator. These operations may be fast, or not, but why do them if you don't have to? A Map.Entry gives you both key and value, together, in the most efficient manner possible.

    1.for (Iterator it = map.entrySet().iterator(); it.hasNext(); ) { 2. Map.Entry e = (Map.Entry) it.next(); 3. Foo key = (Foo) e.getKey(); 4. Bar value = (Bar) e.getValue(); 5. // now do something with key and value 6.}

    Under JDK 5 and later it's a little nicer:

    1.for (Map.Entry e : map.entrySet()) { 2. Foo key = e.getKey(); 3. Bar value = e.getValue(); 4. // now do something with key and value 5.}

    The SortedMap interface (with the implementation TreeMap) should be your friend.The interface has the methods:

    keySet() which returns a set of the keys in ascending order values() which returns a collection of all values in the ascending order of the corresponding keys

    However, the keys must have a meaningful order. Otherwise you can used the LinkedHashMap where the order is determined by the insertion order.

    Example,public static void main(String[] args) {

    Map hashMap = new HashMap();hashMap.put(10, null);

  • Core JavahashMap.put(2, "First");hashMap.put(1, "First");hashMap.put(null, null);hashMap.put(null, "Second");hashMap.put(3, null);

    for (Integer key : hashMap.keySet()) {System.out.println( key + " " + hashMap.get(key));

    }

    }

    Output:null Second1 First2 First3 null10 null

    HashMap : A HashMap contains values based on the key. It implements the Map

    interface and extends AbstractMap class. It contains only unique elements. It may have one null key and multiple null values. It maintains no order.

    Hierarchy of HashMap Class :class Simple{ public static void main(String args[]){ HashMap hm=new HashMap();

    hm.put(100,"Amit"); hm.put(101,"Vijay"); hm.put(102,"Rahul");

    Set set=hm.entrySet(); Iterator itr=set.iterator();

    while(itr.hasNext()){ Map.Entry m=(Map.Entry)itr.next(); System.out.println(m.getKey()+" "+m.getValue()); } }

  • Core Java}The HashMap class uses a hashtable 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 HashMap class supports four constructors. The first form constructs a default hash map:

    HashMap( )

    The second form initializes the hash map by using the elements of m:

    HashMap(Map m)

    The third form initializes the capacity of the hash map to capacity:

    HashMap(int capacity)

    The fourth form initializes both the capacity and fill ratio of the hash map by using its arguments:

    HashMap(int capacity, float fillRatio)

    LinkedHashMap : A LinkedHashMap contains values based on the key. It implements the

    Map interface and extends HashMap class. It contains only unique elements. It may have one null key and multiple null values. It is same as HashMap instead maintains insertion order.

  • Core JavaTree Map :

    A TreeMap contains values based on the key. It implements the NavigableMap interface and extends AbstractMap class.

    It contains only unique elements. It cannot have null key but can have multiple null values. It is same as HashMap instead maintains ascending order.

    Example,public static void main(String[] args) { // Create a TreeMap and populate it with elements TreeMap treeMap = new TreeMap(); treeMap.put("key_1","element_1"); treeMap.put("key_2","element_2"); treeMap.put("key_3","element_3"); // Get a set of all the entries (key - value pairs) contained in the TreeMap Collection entrySet = treeMap.entrySet(); // Obtain an Iterator for the entries Set Iterator it = entrySet.iterator(); // Iterate through TreeMap entries System.out.println("TreeMap entries : "); while(it.hasNext())

    System.out.println(it.next()); }

    TreeMap entries : key_1=element_1key_2=element_2key_3=element_3

  • Core Java

    HashTable :

    A HashTable is an Array of list. Each list is known as a bucket. The position of the bucket is

    identified by calling hashcode() method. A Hashtable contains values based on the key. It implements the Map interface and extends Dictionary class. It contains only unique elements It may not have any null key or value It is synchronized

    Syntax :public class Hashtable extends Dictionary implements Map, Cloneable, Serializable

    To successfully store and retrieve objects from a hashtable, the objects used as keys must implement the hashCode method and the equals method.

    This example creates a hashtable of numbers. It uses the names of the numbers as keys: Hashtable numbers = new Hashtable(); numbers.put("one", 1); numbers.put("two", 2); numbers.put("three", 3);To retrieve a number, use the following code: Integer n = numbers.get("two"); if (n != null) { System.out.println("two = " + n); }

    HashMap vs HashTable :

    HashMap HashTableIt is not synchronized It is synchronizedCan contain one null key and multiple null values

    Can contain neither null key nor null values

  • Core JavaHashMap vs. TreeMap vs. Hashtable vs. LinkedHashMap :There are 4 commonly used implementations of Map in Java SE

    1) HashMap,2) TreeMap,3) Hashtable and4) LinkedHashMap.

    HashMap is implemented as a hash table, and there is no ordering on keys or values.

    TreeMap is implemented based on red-black tree structure, and it is ordered by the key.

    LinkedHashMap preserves the insertion order Hashtable is synchronized, in contrast to HashMap.

    HashMap :If key of the HashMap is self-defined objects, then equals() and hashCode() contract need to be followed.

    class TestDog {String color;

    TestDog(String c) {color = c;

    }

    public String toString() {return color + " dog";

  • Core Java}

    }

    public class HashMapDemo {/** * @param args */public static void main(String[] args) {

    // TODO Auto-generated method stubHashMap hashMap = new

    HashMap();TestDogSample d1 = new TestDogSample("red");TestDogSample d2 = new TestDogSample("black");TestDogSample d3 = new TestDogSample("white");TestDogSample d4 = new TestDogSample("white");hashMap.put(d1, 10);hashMap.put(d2, 15);hashMap.put(d3, 5); // HashMap accepts duplicates key herehashMap.put(d4, 20);

    // print sizeSystem.out.println(hashMap.size());

    // loop HashMapfor (Entry entry : hashMap.entrySet())

    {System.out.println(entry.getKey().toString() + " - "

    + entry.getValue());}

    }

    }

    Output :4white dog 5black dog 15red dog 10white dog 20

    Note here, we add white dogs twice by mistake, but the HashMap takes it. This does not make sense, because now we are confused how many white dogs are really there.The Dog class should be defined as follows:class TestDogSample {

    String color;

    TestDogSample(String c) {color = c;

  • Core Java}

    public String toString() {return color + " dog";

    }

    // Override those two methods hashCode() equals() from Object Class

    public int hashCode() {return color.length();

    }

    public boolean equals(Object obj) {return this.color == ((TestDogSample)obj).color;

    }}

    public class TestHashMap {/** * @param args */public static void main(String[] args) {

    // TODO Auto-generated method stubHashMap hashMap = new

    HashMap();TestDogSample d1 = new TestDogSample("red");TestDogSample d2 = new TestDogSample("black");TestDogSample d3 = new TestDogSample("white");TestDogSample d4 = new TestDogSample("white");hashMap.put(d1, 10);hashMap.put(d2, 15);hashMap.put(d3, 5); // HashMap does not accept

    duplicates key herehashMap.put(d4, 20);

    // print sizeSystem.out.println(hashMap.size());

    // loop HashMapfor (Entry entry : hashMap.entrySet())

    {System.out.println(entry.getKey().toString() + " - "

    + entry.getValue());}

    }

    }Now the output is:

    3red dog 10

  • Core Java

    white dog 20black dog 15

    The reason is that HashMap doesnt allow two identical elements. By default, the hashCode() and equals() methods implemented in Object class are used. The default hashCode() method gives distinct integers for distinct objects, and the equals() method only returns true when two references refer to the same object

    HashMap vs TreeMap :

    HashMap TreeMapLookup-array structure, based on hashCode(), equals() implementations, O(1) runtime complexity for inserting and searching, unsorted

    Tree structure, based on compareTo() implementation, O(log(N)) runtime complexity for inserting and searching, sorted

    Does not support duplicate key Does not support duplicate key

    Its not synchronized, To make it synchronized we have to explicitly call Collections.synchronizedMap(mapName )

    Its not synchronized, To make it synchronized we have to explicitly call Collections.synchronizedMap(mapName )

    HashMap allows null as both keys and values,contain 1 null key and multiple null values

    Does not contain null key but contains multiple null values

    Its fast compared to treemap Its slow compared to hashmap

    It implements Map interfaceMap implements Hashmap

    It implements one more interface called NavigableMapMap extends SortedMap extends NavigableMap Implements TreeMap

    Unordered map Ordered map. TreeMap order can be customized using Comparator and Comparable interfaces.

  • Core JavaWhat is fail-fast?

    The concept of fail-fast comes with iterators. When an Iterator object is created and iteration is going on, the HashMap elements cannot be modified (like addition or deletion of elements cannot be done). This is explained programmatically in ConcurrentModificationException.

    About Hashing and Hashcode

    HashCode

    Comparing two strings letter by letter in a for loop is a time taking process.

    To make faster, the JVM converts each string into an integer number called hashcode.

    Different strings with different sequence of characters have different hashcodes.

    Comparison with integer numbers gives maximum performance.

    Usage of hashcode numbers for comparison, searching of duplicate elements and identification is

    faster.

    Hashing Hashing is process of converting a string or object into a 32-bit integer number.

    Two objects are said to be equal if their hashcodes are same.

    hashCode() is used in combination of equals() method.

    When compared, hashing is done automatically by the JVM.

    Hashing, in data structures, is done implicitly in the basic operations with add(), contains(),

    remove() and size() etc. Hashing is more useful to compare the sets of large content.

    HashMap vs HashSet:

    Parameter HashMap HashSetInterface This is core difference

    among them. HashMap implements Map interface

    HashSet implement Set interface

    Method for storing data It stores data in a form of key->value pair. So it uses put(key,value) method for storing data

    It uses add(value) method for storing data

    Duplicates HashMap allows duplicate value but not duplicate keys

    HashSet does not allow duplicate values.

    Performance It is faster than It is slower than HashMap

  • Core Javahashset as values are stored with unique keys

    HashCode Calculation In hash map hashcode value is calculated using key object

    In this,hashcode is calculated on the basis of value object. Hashcode can be same for two value object so we have to implement equals() method. If equals() method return false then two objects are different.

    Value Inertion use put() method to insert key and value into HashMap in Java.

    Use add() method to put elements into Set.

    null HashMap can allow one null key + multiple null values

    HashSet allows only one null key

    Similarities :1) Both HashMap and HashSet are hash based collection in Java.2) Both HashMap and HashSet are not synchronized and can not be shared between multiple threads.3) Iterator returned by HashMap's keySet() and HashSet are fail-fast and they throw ConcurrentModificationException if they detect any structural change in Collection.

    4) Both HashMap and HashSet provided constant time performance for basic operations like put(), get() etc.5) Both HashSet and HashMap allows null values.

    hashCode() vs equals() .?

    The contract between hashCode and equals method,

    if two objects are equal, that is obj1.equals(obj2) is true then, obj1.hashCode() and obj2.hashCode() must return same integer.

    Why do we need to override equals() and hashcode() .?1) If 2 objects are same then they must return same value in hashcode() and equals() method whenever invoked.2) It is not necessary that 2 different objects must have different hashcode values. It might be possible that they share common hash bucketsfor example,object1 amyobject2 mayboth has different hashcode but may possible to share same hash buckets

  • Core Java

    3) JVM assigns unique hashcode values to each object when they are created in memory and if developers dont override the hashcode method then there is no way the 2 objects returns same hashcode values

    Example,

    class employeetest {private String name;private int id;public employeetest(String empname, Integer empid) {

    this.name = empname;this.id = empid;

    }

    public String toString() {return name + " " + id;

    }

    /*public int hashCode() {return this.name.length();

    }*/

    public boolean equals(Object obj) {return this.name == ((employeetest)obj).name;

    }}

    public class HashSetDemo {/** * @param args */public static void main(String[] args) {

    // TODO Auto-generated method stubHashSet set = new HashSet();set.add(new employeetest("Praveen", 12));set.add(new employeetest("Praveen", 12));for (employeetest empObj : set) {

    System.out.println(empObj.toString());

    obj1

    obj2

  • Core Java}

    }

    }

    output :Praveen 12Praveen 12

    Note: The same code has equals() method as commented and hashcode() method as uncommented will get the same result like above

    If both methods overrides here you will get the exact output and duplicates are not allowed in collection here

    class employeetest {private String name;private int id;public employeetest(String empname, Integer empid) {

    this.name = empname;this.id = empid;

    }

    public String toString() {return name + " " + id;

    }

    public int hashCode() {return this.name.length();

    }

    public boolean equals(Object obj) {return this.name == ((employeetest)obj).name;

    }}

    public class HashSetDemo {/** * @param args */public static void main(String[] args) {

    // TODO Auto-generated method stubHashSet set = new HashSet();set.add(new employeetest("Praveen", 12));set.add(new employeetest("Praveen", 12));for (employeetest empObj : set) {

    System.out.println(empObj.toString());}

    }

    }

  • Core Java

    output :Praveen 12

    HashTable, HashMap and HashSet are the Collection classes in java.util package that make use of hashing algorithm to store objects. In all these Collection classes except HashSet, objects are stored as key-value pairs. For the storage and the retrieval of any user-defined objects it is a good practice to override the following methods which is mentioned below,

    hashCode() equals()

    These methods are available in the Object class and hence available to all java classes. Using these two methods, an object can be stored or retrieved from a Hashtable, HashMap or HashSet.

    hashCode() method

    This method returns a hashcode value as an int for the object.

    Default implementation for hashcode() should be overridden in order to make searching of data faster.

    The implementation of hashCode() method for an user-defined object should be calculated based on the properties of the class which we wish to consider.

    equals() method

    This method returns a boolean which specifies whether two objects are equal or not.

    The default implementation of equals() method given by the Object Class uses the == operator to compare two object references, and returns true only if they refer to the same object.

    But, we can meaningfully re-define this equals() method to have en equality check based on our own criteria.

  • Core JavaDesign Patterns :

    A design pattern is a well-proved solution for solving the specific problem/task.

    Design patterns are programming language independent strategies for solving the common object-oriented design problems.

    A design pattern represents an idea, not a particular implementation.

    By using the design patterns you can make your code more flexible, reusable and maintainable.

    It is the most important part because JAVA internally follows design patterns.

    Understanding the problem without using Design Patterns :

    Problem Given:Suppose you want to create a class for which only a single instance (or object) should be created and that single object can be used by all other classes.Solution :

    Singleton design pattern is the best solution of above specific problem. So, every design pattern has some specification or set of rules for solving the problems.

    Advantage of design pattern They are reusable in multiple projects. They provide the solutions that help to define the system

    architecture. They capture the software engineering experiences. They provide transparency to the design of an application. They are well-proved and testified solutions since they have been

    built upon the knowledge and experience of expert software developers.

    Design patterns don't guarantee an absolute solution to a problem. They provide clarity to the system architecture and the possibility of building a better system.

    When should we use the design patterns?

    We must use the design patterns during the analysis and requirement phase of SDLC (Software Development Life Cycle).

  • Core JavaTypes of design patterns :Basically, design patterns are categorized into two parts:

    1) Core java (or JavaSE) Design Patterns. Creational Design Pattern Structural Design Pattern Behavioral Design Pattern

    2) JavaEE (J2EE) Design Patterns. Presentation Layer Design Pattern Business Layer Design Pattern Data Layer Design Pattern

    Core Java Design PatternsIn core java, there are mainly three types of design patterns, which are further divided into their sub-parts:

    Creational Design Pattern Structural Design Pattern Behavioral Design Pattern

    Factory Pattern Adapter Pattern Chain Of Responsibility Pattern

    Abstract Factory Pattern

    Bridge Pattern Command Pattern

    Singleton Pattern Composite Pattern Interpreter Pattern

    Prototype Pattern Decorator Pattern Iterator Pattern

    Builder Pattern. Facade Pattern Mediator Pattern

    Flyweight Pattern Memento Pattern

    Proxy Pattern Observer Pattern

    State Pattern

    Strategy Pattern

    Template Pattern

    Visitor Pattern

  • Core JavaCreational design patterns :

    Creational design patterns are concerned with the way of creating objects.

    These design patterns are used when a decision must be made at the time of instantiation of a class (i.e. creating an object of a class).

    But everyone knows an object is created by using new keyword in java.For example,

    Employee emp = new Employee();Hard-Coded code is not the good programming approach. Here, we are creating the instance by using the new keyword. Sometimes, the nature of the object must be changed according to the nature of the program. In such cases, we must get the help of creational design patterns to provide more general and flexible approach.

    Factory Method Pattern :

    A Factory Pattern or Factory Method Pattern says that just define an interface or abstract class for creating an object but let the subclasses decide which class to instantiate.

    In other words, subclasses are responsible to create the instance of the class. The Factory Method Pattern is also known as Virtual Constructor.

    Advantage of Factory Design Pattern :

    Factory Method Pattern allows the sub-classes to choose the type of objects to create.

    Usage of Factory Design Pattern :

    When a class doesn't know what sub-classes will be required to create

    When a class wants that its sub-classes specify the objects to be created.

    When the parent classes choose the creation of objects to its sub-classes.

  • Core JavaUML for Factory Method Pattern :

    We are going to create a Plan abstract class and concrete classes that extends the Plan abstract class. A factory class GetPlanFactory is defined as a next step.GenerateBill class will use GetPlanFactory to get a Plan object. It will pass information (DOMESTICPLAN / COMMERCIALPLAN / INSTITUTIONALPLAN) to GetPalnFactory to get the type of object it needs.

    Example Code ,abstract class Plan{ protected double rate; abstract void getRate(); public void calculateBill(int units){ System.out.println(units*rate); }}//end of Plan class

    class DomesticPlan extends Plan{ //@override

  • Core Java public void getRate(){ rate=3.50; } }//end of DomesticPlan class.

    class CommercialPlan extends Plan{ //@override public void getRate(){ rate=7.50; } }//end of CommercialPlan class.

    class InstitutionalPlan extends Plan{ //@override public void getRate(){ rate=5.50; } }//end of InstitutionalPlan class.

    Factory Pattern Class Applies here :

    class GetPlanFactory{

    //use getPlan method to get object of type Plan public Plan getPlan(String planType){ if(planType == null){ return null; }

    if(planType.equalsIgnoreCase("DOMESTICPLAN")) { return new DomesticPlan(); } else if(planType.equalsIgnoreCase("COMMERCIALPLAN")){ return new CommercialPlan(); } else if(planType.equalsIgnoreCase("INSTITUTIONALPLAN")) { return new InstitutionalPlan(); }

  • Core Java return null; }}//end of GetPlanFactory class.

    Implementation Class :

    class GenerateBill{ public static void main(String args[])throws IOException{ GetPlanFactory planFactory = new GetPlanFactory(); System.out.print("Enter the name of plan for which the bill will be generated: "); BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

    String planName=br.readLine(); System.out.print("Enter the number of units for bill will be calculated: "); int units=Integer.parseInt(br.readLine());

    Plan p = planFactory.getPlan(planName); //call getRate() method and calculateBill()method of DomesticPaln.

    System.out.print("Bill amount for "+planName+" of "+units+" units is: "); p.getRate(); p.calculateBill(units); } }//end of GenerateBill class.

    Singleton design pattern :

    Singleton Pattern says that just "define a class that has only one instance and provides a global point of access to it".

    In other words, a class must ensure that only single instance should be created and single object can be used by all other classes.

    There are two forms of singleton design pattern, Early Instantiation : creation of instance at load time.

  • Core Java Lazy Instantiation : creation of instance when required.

    Advantage of Singleton design pattern :

    Saves memory because object is not created at each request. Only single instance is reused again and again.

    Usage of Singleton design pattern : Singleton pattern is mostly used in multi-threaded and database

    applications. It is used in logging, caching, thread pools, configuration settings etc.

    Uml of Singleton design pattern :

    How to create Singleton design pattern ?To create the singleton class, we need to have static member of class, private constructor and static factory method.

    Private Static member: It gets memory only once because of static, it contains the instance of the Singleton class.

    Private constructor: It will prevent to instantiate the Singleton class from outside the class.

    Public Static factory method: This provides the global point of access to the Singleton object and returns the instance to the caller.

  • Core Java

    Understanding early Instantiation of Singleton Pattern :In such case, we create the instance of the class at the time of declaring the static data member, so instance of the class is created at the time of class loading.Let's see the example of singleton design pattern using early instantiation.

    class A{private static A obj = new A(); //Early, instance will be created at

    load time private A(){} public static A getA(){

    return obj;

    }

    public void doSomething(){ //write your code }}

    Understanding lazy Instantiation of Singleton Pattern :In such case, we create the instance of the class in synchronized method or synchronized block, so instance of the class is created when required.Let's see the simple example of singleton design pattern using lazy instantiation.

    class A{ private static A obj; private A(){} public static A getA(){ if (obj == null){ synchronized(A.class){

    if (obj == null){obj = new Singleton(); //instance will be created at

  • Core Javarequest time

    }}

    } return obj; } public void doSomething(){ //write your code }}

    Significance of Classloader in Singleton Pattern : If singleton class is loaded by two classloaders, two instance of

    singleton class will be created, one for each classloader.

    Significance of Serialization in Singleton Pattern :

    If singleton class is Serializable, you can serialize the singleton instance. Once it is serialized, you can deserialize it but it will not return the singleton object.

    To resolve this issue, you need to override the readResolve() method that enforces the singleton. It is called just after the object is deserialized. It returns the singleton object.

    public class A implements Serializable {//your code of singletonprotected Object readResolve() {

    return getA();}

    }

    Understanding Real Example of Singleton Pattern :We are going to create a JDBCSingleton class. This JDBCSingleton class contains its constructor as private and a private static instance jdbc of itself.JDBCSingleton class provides a static method to get its static instance to the outside world. Now, JDBCSingletonDemo class will use JDBCSingleton class to get the JDBCSingleton object.

  • Core Java

    Example Singleton class ,class JDBCSingleton { //Step 1 // create a JDBCSingleton class. //static member holds only one instance of the JDBCSingleton class. private static JDBCSingleton jdbc; //JDBCSingleton prevents the instantiation from any other class. private JDBCSingleton() { } //Now we are providing gloabal point of access.public static JDBCSingleton getInstance() { if (jdbc==null) { jdbc=new JDBCSingleton(); } return jdbc; } // to get the connection from methods like insert, view etc. private static Connection getConnection()throws ClassNotFoundException, SQLException { Connection con=null; Class.forName("com.mysql.jdbc.Driver"); con= DriverManager.getConnection("jdbc:mysql://localhost:3306/ashwanirajput", "root", "ashwani"); return con; }

  • Core Java //to insert the record into the database public int insert(String name, String pass) throws SQLException { Connection c=null; PreparedStatement ps=null; int recordCounter=0; try { c=this.getConnection(); ps=c.prepareStatement("insert into userdata(uname,upassword)values(?,?)"); ps.setString(1, name); ps.setString(2, pass); recordCounter=ps.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally{ if (ps!=null){ ps.close(); }if(c!=null){ c.close(); } } return recordCounter; }

    //to view the data from the database public void view(String name) throws SQLException { Connection con = null;

    PreparedStatement ps = null;ResultSet rs = null;

    try {

  • Core Java con=this.getConnection(); ps=con.prepareStatement("select