Tuesday, 15 September 2015

Java CollectionsTutorial

What is Java Collections?

The Java collections framework (JCF) is a set of classes and interfaces that implement commonly reusable collection data structures.

Almost all collections in Java are derived from the java.util.Collection interface.


The Collection interface is a subinterface of java.lang.Iterable, so any Collection may be the target of a for-each statement.

Java Collection simply means a single unit of objects

Interfaces and Classes Distribution:


The JCF consist of the following types of Interfaces and Classes.




List

A List is an ordered Collection (sometimes called a sequence). Lists may contain duplicate elements. Elements can be inserted or accessed by their position in the list, using a zero-based index.

ArrayList

  • Java ArrayList class uses a dynamic array for storing the elements.It extends AbstractList class and implements List interface.
  • Java ArrayList class can contain duplicate elements.
  • Java ArrayList class maintains insertion order.
  • Java ArrayList class is non synchronized.
  • Java ArrayList allows random access because array works at the index basis.
  • In Java ArrayList class, manipulation is slow because a lot of shifting needs to be occurred if any element is removed from the array list.

Declaration:

ArrayList<String> al  =  new ArrayList<String>();//creating new generic arraylist


Examples:

http://www.javatpoint.com/ArrayList-in-collection-framework


HashMap


HashMap is a Hash table based implementation of the Map interface .

The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls

It neither does any kind of sorting to the stored keys and Values.

HashMap maintains key and value pairs and often denoted as HashMap<Key, Value> or HashMap<K, V>.


Example:

package com.java2novice.hashmap;
import java.util.HashMap;
public class MyBasicHashMap {
    public static void main(String a[]){
        HashMap<String, String> hm = new HashMap<String, String>();
        //add key-value pair to hashmap
        hm.put("first", "FIRST INSERTED");
        hm.put("second", "SECOND INSERTED");
        hm.put("third","THIRD INSERTED");
        System.out.println(hm);
        //getting value for the given key from hashmap
        System.out.println("Value of second: "+hm.get("second"));
        System.out.println("Is HashMap empty? "+hm.isEmpty());
        hm.remove("third");
        System.out.println(hm);
        System.out.println("Size of the HashMap: "+hm.size());
    }
}


Output:
{second=SECOND INSERTED, third=THIRD INSERTED, first=FIRST INSERTED}
Value of second: SECOND INSERTED
Is HashMap empty? false
{second=SECOND INSERTED, first=FIRST INSERTED}
Size of the HashMap: 2


Thanks to : http://www.java2novice.com/

An excellent tutorial is available on  http://www.java2novice.com/java-collections-and-util/hashmap/basic-operations/

No comments:

Post a Comment