Introduction to Collections API

download Introduction to Collections API

of 51

Transcript of Introduction to Collections API

  • 8/8/2019 Introduction to Collections API

    1/51

    Introduction to Collections API

    As the name indicates, collections is a group of objects known as its elements. Basicallyit is a package of data structures that includes ArrayLists , LinkedLists , HashSets , etc.A collection is simply an object that groups multiple elements into a single unit. It is alsocalled as a container sometimes. It is used to store, retrieve, manipulate, andcommunicate aggregate data. Typically, it represents data items that form a natural groupand allows duplicate elements while others do not. It consists of both ordered andunordered elements. There is no direct implementation of this interface however SDK

    provides implementations of more specific sub interfaces like Set and List. Themanipulation and passing of collections is done by this interface.

    The Two "standard" constructors should be provided by all the general-purpose

    Collection implementation classes. These classes typically implement Collectionindirectly through one of its sub interfaces.

    1. Void (no arguments) constructor which creates an empty collection. 2. Constructor with a single argument of type Collection, which creates a new

    collection with the same elements as its argument.

    The user can copy any collection using void constructor to produce an equivalentcollection of the desired implementation type. As interfaces cannot contain constructorsthere is no way to enforce this convention. However all of the general-purpose Collectionimplementations comply this in the Java platform libraries.

    The Java Collections API:

    Java Collections of API (Application Programming Intreface) Consists of severalinterfaces, and classes that implement those interfaces, within the java.util package. It

    provides tools for maintaining a data container of objects. Each primitive value must bewrapped in an object of its appropriate wrapper class ( Boolean , Character , Integer ,Double , etc. ) to maintain a collection of primitive data. It is an alternative tool to thecreation of custom data structures.

    You must be familiar with collections if you have worked with Java programming

    language . Collection implementations included Vector , Hashtable , and array areavailable in earlier (pre-1.2) versions of the Java platform, but those versions do notinclude the collections framework. Hence the new version of the Java platform containsthe collections framework.

    http://www.roseindia.net/java/jdk6/introduction-to-CollectionFramework.shtmlhttp://www.roseindia.net/java/jdk6/index.shtmlhttp://www.roseindia.net/java/jdk6/Changes-in-IO.shtml
  • 8/8/2019 Introduction to Collections API

    2/51

    Introduction to Collections Framework

    Collections Framework:

    The Collections Framework provides a well-designed set of interfaces and classes for storing and manipulating the groups of data into a single unit. The collections framework is a unified architecture which is used to represent and manipulate collections. Theframework allows the collections to get manipulated independently, additionally itreduces the programming efforts and increases performance.

    It includes implementation of interfaces and algorithms. Basically it is a unifiedarchitecture that consists the following collections:

    1. Interfaces: These are the abstract data types that represent collections. With thehelp of interfaces we manipulate collections independently. A hierarchy isgenerally formed with interfaces in object-oriented languages .

    2. Implementations: They are the reusable data structures with the concreteimplementations of the collection interfaces.

    3. Algorithms: Algorithms are used to perform computations, such as searching,sorting etc on the objects that implement collection interfaces. They providereusable functionality i.e. the same method can be used with differentimplementations of the collection interfaces. Hence they are also said to be

    polymorphic.

    4. General-purpose Implementations: These are the primary implementations of the collection interfaces.

    5. Infrastructure: Interfaces that provide essential support for the collectioninterfaces.

    6. Array Utilities: Utility functions for arrays of primitives and reference objects.This functionality was added to the Java platform as a part of the CollectionsFramework.

    Advantages of collections framework:

    The Java Collections Framework provides the following benefits:

    1. Reduces the efforts to learn and use the new APIs: We need not to learnmultiple ad hoc collection APIs.

    http://www.roseindia.net/java/jdk6/Collection-Interfaces.shtmlhttp://www.roseindia.net/java/jdk6/index.shtmlhttp://www.roseindia.net/java/jdk6/introduction-collections-api.shtml
  • 8/8/2019 Introduction to Collections API

    3/51

    2. Fosters software reuse: It provides a standard interface for collections thatfosters software reuse and also provides algorithms to manipulate them.

    3. Reduces the efforts to design new APIs: It reduces the efforts required to designand implement APIs by eliminating the need to produce ad hoc collections APIs.

    4. Reduces the programming efforts: It provides useful data structures andalgorithms that reduces programming efforts due to which we need not to writethem ourselves.

    5. Increases performance: It provides high-performance implementations of usefuldata structures and algorithms that increases the performance.

    6. Provides interoperability between the unrelated APIs: It helps in establishinga common language to pass collections back and forth to provide interoperability

    between the unrelated APIs.7. Provides resizable capability: Collection is resizable i.e. it can grow

    dynamically.Disadvantages of collections framework:

    1. It must cast to correct type.2. avoids the compile-time type checking.

    Collection Interfaces

    The Collections Framework is made up of a set of interfaces for storing andmanipulating groups of data into a single unit. It consists of several interfaces, and classesthat implement those interfaces, contained within the java.util package. It provides toolsfor maintaining a data container of objects.

    Different interfaces describe different types of functionalities.The following diagrams shows the framework of core collection interfaceshierarchy.

    http://www.roseindia.net/java/jdk6/set-interface.shtmlhttp://www.roseindia.net/java/jdk6/index.shtmlhttp://www.roseindia.net/java/jdk6/introduction-to-CollectionFramework.shtml
  • 8/8/2019 Introduction to Collections API

    4/51

    Table of the ordered and unordered Collection interfaces shown as:

    Interfacename Ordered

    Allowsduplicates

    Maps keyto object

    Collection No Yes NoSet No No NoList Yes Yes NoMap No No YesSortedSet Yes No NoSortedMap Yes No Yes

    Collection Interface:

    The Collection interface is the root interface for the Java collections hierarchy. It isextended by the List , Set , and the SortedSet interfaces. The Collection interface is usedto represent a group of objects, or elements. Typically, it represents data items that form anatural group. Some collection allows duplicate elements while others do not. It consistsof both ordered and unordered elements.

    The declaration of the Collection interface is shown as:

    public interface Collection..

    The syntax tells that, the declared interface is a generic interface i.e. when youdeclare a Collection instance you should specify the type of object contained in thecollection.This interface supports basic operations like adding and removing. When you try to

    remove an element, only a single instance of the element in the collection is removed, if itis available.

    Following methods can be used for adding and deleting an element respectively.

    boolean add(Object element)boolean remove(Object element)

  • 8/8/2019 Introduction to Collections API

    5/51

    The list of other methods belonging to the Collection interface is shown in the tablegiven below

    Method Usesadd(E o)

    Adds the specified element to this set if it is not already present

    (optional operation).

    clear() Removes all of the elements from this set (optional operation).

    contains(Object o) Returns true if this set contains the specified element.

    equals(Object o) Compares the specified object with this set for equality.

    hashCode() Returns the hash code value for this set.

    isEmpty()Returns true if this set contains no elements.

    iterator() Returns an iterator over the elements in this set.

    remove(Object o) Removes the specified element from this set if it is present(optional operation).

    size() Returns the number of elements in this set (its cardinality).

    Set Interface

    The Set interface extends the Collection interface. It neither contains duplicate elements

    nor maps a key value to an object. It permits a single element to be null . The Setinterface contains only methods inherited from Collection interface, these are shown inthe table given below:

    http://www.roseindia.net/java/jdk6/List-Queue-interface.shtmlhttp://www.roseindia.net/java/jdk6/index.shtmlhttp://www.roseindia.net/java/jdk6/Collection-Interfaces.shtml
  • 8/8/2019 Introduction to Collections API

    6/51

    Method Uses

    add( ) Adds an object to the collection clear( ) Removes all objects from the collection

    contains( ) Returns true if a specified object is an element within thecollection

    isEmpty( ) Returns true if the collection has no elements

    iterator( ) Returns anIterator object for the collection which may

    be used to retrieve an object remove( ) Removes a specified object from the collection size( ) Returns the number of elements in the collection

    In the Java platform, Collections Framework provides three general-purpose Setimplementation-classes:

    HashSet TreeSet LinkedHashSet

    HashSet:This is a class which stores its elements in a hash table and doesn't allow to storeduplicate collections. This class permits the null element and is used to perform the

    basic operations such as add, remove, contains and size . This is the best way to performset implementation.

    TreeSet:The TreeSet implementation is useful when you need to extract elements from acollection in a sorted manner. The elements added to a TreeSet are sortable in an order. Itis generally faster to add elements to a HashSet , then converting the collection to aTreeSet for sorted traversal.

    LinkedHashSet:It is a class which is implements both the Hash table and linked list implementation of theSet interface. This implementation differs from HashSet that it maintains a doubly-linkedlist. The orders of its elements are based on the order in which they were inserted into theset (insertion-order).

    SortedSet Interface :

    The SortedSet interface extends the Set interface. It maintains its elements in ascendingorder. It neither contains duplicate elements nor maps a key value to an object. It

  • 8/8/2019 Introduction to Collections API

    7/51

    permits a single element to be null. In addition to methods of the Set interface, it also provides two following methods:

    first( )last( )

    The first( ) method returns the first (lowest) element currently in the collection while thelast( ) method returns the last (highest) element currently in the collection.

    Let see an example that stores a group of numbers to the Hash table using HashSet class.

    import java.util.*;

    public class SetDemo { public static void main(String args[]) {

    int count[]={ 34 , 22 , 10 , 60 , 30,22 }; Set set = new HashSet();

    try{

    for ( int i= 0 ; i< 5 ; i++){ set.add(count[i]); } System.out.println(set);

    TreeSet sortedSet= new TreeSet(set); System.out.println( "The sorted list is:" ); System.out.println(sortedSet);

    System.out.println( "The First element of the set is: " +(Integer)sortedSet.first());

    System.out.println( "The last element of the set is: " +(Integer)sortedSet.last());

    } catch (Exception e){} }}

    Output of the Program:

    C:\nisha>javacSetDemo.java

    C:\nisha>javaSetDemo[34, 22, 10, 30, 60]The sorted list is:[10, 22, 30, 34, 60]The First element of the set is: 10The last element of

  • 8/8/2019 Introduction to Collections API

    8/51

    the set is: 60

    C:\nisha>

    This program creates a HashSet and adds a group of numbers, including a number "22"

    twice. The program than prints out the list of numbers in the set, note that the duplicatenumber is not added to the set. Then the program treats the set as a TreeSet and displaysthe sorted list of the set. The first( ) and the last( ) methods display the first & lastelements of the set respectively.

    Introduction to List and Queue Interface

    List Interface :

    The List interface extends the Collection interface to define an ordered collection. It is

    also known as the sequence collection which permits duplicates element to accommodatein the set but does not map a key value to an object. It permits one or more elements to be null.

    This interface adds position-oriented operations such as insert an element, get an elementas well as remove or change an element based on their numerical position in the list. Italso performs search operation to allow searching a specified object in the list and returnsits numerical position.

    In addition to methods of the Set interface, it provides following three methods shown inthe table below:

    Method Uses get( ) Returns the element at the specified index position in this collection

    listIterator( ) Returns a List Iterator object for the collection which may then beused to retrieve an object

    remove( ) Removes the element at the specified index position in thiscollection

    http://www.roseindia.net/java/jdk6/map-interface.shtmlhttp://www.roseindia.net/java/jdk6/index.shtmlhttp://www.roseindia.net/java/jdk6/set-interface.shtml
  • 8/8/2019 Introduction to Collections API

    9/51

    Queue Interface:

    A Queue interface extends the Collection interface to define an ordered collection for holding elements in a FIFO (first-in-first-out) manner to process them i.e. in a FIFOqueue the element that is inserted firstly will also get removed first.

    Besides basic collection operations, queues also provide additional operations such asinsertion , removal , and inspection .The Methods of this interface are as follows.

    Method Uses

    peek( ) Returns an element but if queue is empty then it returnsnull

    poll( ) Removes an element but returns null if the queue isempty.

    In the Java platform, Collections Framework provides three general-purpose List andQueue implementation-classes:

    ArrayListLinkedListRunArrayList

    The following program demonstrates the implementation of List and Queue interfaces.

    import java.util.*;

    public class ListQueueDemo { public static void main(String args[]) {

    int numbers[]={ 34 , 22 , 10 , 60 , 30 }; List list = new ArrayList(); try { for ( int i= 0 ; i< 5 ; i++){ list.add(numbers[i]); } System.out.println( "the List is: " ); System.out.println(list); LinkedList queue = new LinkedList(); for ( int i= 0 ; i< 5 ; i++){ queue.addFirst(numbers[i]);

    } System.out.println( "The Oueue is: " ); System.out.println(queue); queue.removeLast(); System.out.println( "After removing last element the queue is: " + queue);

    } catch (Exception e){} }}

  • 8/8/2019 Introduction to Collections API

    10/51

    Output of the Program:

    C:\nisha>javacListQueueDemo.java

    C:\nisha>javaListQueueDemothe List is:[34, 22, 10, 60, 30]The Oueue is:[30, 60, 10, 22, 34]After removing lastelement the queue is:[30, 60, 10, 22]

    C:\nisha>This program creates a List and Queue, and inserts a group of numbers in these lists. The

    program than prints out the list of numbers in the set. The addFirst( ) and removeLast( )methods add and remove an element in a FIFO manner, i.e. the first element of the queueis removed first .

    Introduction to Map and SortedMapInterface

    Map Interface:

    A Map is an object that maps keys to values. It is not an extension of the collectioninterface rather it has own interface hierarchy. Map provides a more general way for storing elements without containing duplicate keys. It allows you to store pairs of elements, termed " keys " and " values ", where each key maps to one value. Thus the keysin a map must be unique.

    The Map interface methods can be broken down into three sets of operations:

    http://www.roseindia.net/java/jdk6/Collection-implementation.shtmlhttp://www.roseindia.net/java/jdk6/index.shtmlhttp://www.roseindia.net/java/jdk6/List-Queue-interface.shtml
  • 8/8/2019 Introduction to Collections API

    11/51

    Altering: The alteration operations allow you to add and remove key-value pairs fromthe map. Both the key and value can be null .Querying: The query operations allow the user to retrieve key/value pairs from the Map.Providing alternative views: This method allow you to work with the different viewswhich can be used to analyze Map key/value Objects.

    Map Methods Returning Views:

    These methods return objects which allow you to traverse the elements of the Map, andalso delete elements from the Map.

    Method Uses

    entrySet()

    Returns a Set view of the mappings contained in the map. Each element inthe set is a Map.Entry object which can have it's key and value elementsaccessed with getKey() and getValue() methods (also has a setValue()method)

    keySet()Returns a Set view of the keys contained in the map. Removing elementsfrom the Set will also remove the corresponding mapping (key and value)from the Map

    values()Returns a Collection view of the values contained in the map. Removingelements from the Collection will also remove the corresponding mapping(key and value) from the Map

    Map.Entry Interface:

    Each element is a map has a key and value. Each key-value pair is saved in a java.util.Map.Entry object. A set of these map entries can be obtained by calling a

    map's entrySet( ) method. Iterating over a map is done by iterating over this set.The Collections Framework provides three general-purpose Map implementation:

    HashMapTreeMapLinkedHashMap

    HashMap:The HashMap is a class which is used to perform some basic operations such asinserting , deleting , and locating elements in a Map . The java.util . HashMap class is

    implemented with and roughly equivalent to a Hashtable except that it isunsynchronized and permits null . It works with the Iterators requires a well-definedimplementation of the method hashCode( ) .

    TreeMap:The TreeMap implementation is useful when you need to traverse the keys from acollection in a sorted manner. The elements added to a TreeMap must be sortable in order to work properly. It is depend upon the size of the specified collection, it may be faster to

  • 8/8/2019 Introduction to Collections API

    12/51

    add elements to a HashMap , then convert the map to a TreeMap for traversing thesorted keys.

    LinkedHashMap:A LinkedHashMap is implemented using both Hash table and linked list implementation

    of the Map interface. This implementation differs from HashMap that maintains adoubly-linked list running through all of its entries in it. The orders of its elements are based on the order in which they were inserted into the set (insertion-order).

    The list of methods supported by Map interface are shown in the table given below:

    Method Uses put(Object key, Objectvalue)

    Associates the specified value with the specified key inthe map.

    clear( ) Removes all mappings from the map

    putAll(Map t)Copies all of the mappings from the specified map tothe map.

    isEmpty( ) Returns true if this map contains no key-valuemappings.

    iterator( ) Returns anIterator object for the collection which

    may be used to retrieve an object.

    remove(Object key) Removes the mapping for this key from this map if it is present.keySet( ) Returns a set view of the keys contained in this map.

    entrySet( ) Returns a set view of the mappings contained in thismap.

    values( ) Returns a collection view of the values contained inthis map. size( ) Returns the number of key-value mappings in this map.

    SortedMap Interface:

    The Collection Framework provides a special Map interface for maintaining elementsin a sorted order called SortedMap . The SortedMap interface extends the Mapinterface which maintains its elements in ascending order. Working with a SortedMap is

    just similar to a SortedSet except, the sort is done on the map keys. In addition to

    methods of the Map interface, it provides two methods shown as:

    firstKey( )lastKey( )

    The firstKey( ) method returns the first (lowest) value currently in the map while thelastKey( ) method returns the last (highest) value currently in the map.

  • 8/8/2019 Introduction to Collections API

    13/51

    Let see an example implementing the HashMap and TreeMap class.

    import java.util.*;

    public class MapDemo { public static void main(String args[]) {

    String days[]={ "Sunday" , "Monday" , "Tuesday" , "Wednesnday" , "Thursday" , "Friday" , "Saturday" }; Map map = new HashMap(); try { for ( int i= 0 ; i< 7 ; i++){ map.put(i, days[i]); }

    TreeMap tMap= new TreeMap(map); //Rerieving all keys System.out.println( "Keys of tree map: " + tMap.keySet()); //Rerieving all values System.out.println( "Values of tree map: " + tMap.values()); //Rerieving the First key and its value System.out.println( "First key: " + tMap.firstKey() +

    " Value: " + tMap.get(tMap.firstKey()) + "\n" );

    //Removing the first key and value System.out.println( "Removing first data: "

    + tMap.remove(tMap.firstKey())); System.out.println( "Now the tree map Keys: " + tMap.keySet()); System.out.println( "Now the tree map contain: " + tMap.values() + "\n" ); //Rerieving the Last key and value System.out.println( "Last key: " + tMap.lastKey() +

    " Value: " + tMap.get(tMap.lastKey()) + "\n" );//Removing the last key and value

    System.out.println( "Removing last data: " + tMap.remove(tMap.lastKey()));

    System.out.println( "Now the tree map Keys: " + tMap.keySet()); System.out.println( "Now the tree map contain: " + tMap.values()); } catch (Exception e){} }}

    Output of this program:

    C:\nisha>javac MapDemo.java

    C:\nisha>java MapDemoKeys of tree map: [0, 1, 2, 3, 4, 5, 6]Values of tree map: [Sunday, Monday, Tuesday,Wednesnday, Thursday, Friday, Saturday]First key: 0 Value: Sunday

    Removing first data: Sunday Now the tree map Keys: [1, 2, 3, 4, 5, 6]

  • 8/8/2019 Introduction to Collections API

    14/51

    Now the tree map contain: [Monday, Tuesday,Wednesnday, Thursday, Friday, Saturday]

    Last key: 6 Value: Saturday

    Removing last data: Saturday Now the tree map Keys: [1, 2, 3, 4, 5] Now the tree map contain: [Monday, Tuesday,Wednesnday, Thursday, Friday]

    C:\nisha>

    The given program stores the values mapping with their keys to the map. The keySet( )method retrieves all keys from the map and the values( ) method retrieves all the valuesadded to a map. The remove( ) method removes the key from the map with its valuespecified in it.

    Introduction to collection

    Implementations

    The Collections Framework provides a well-designed set of interfaces and classes usedfor storing and manipulating groups of data into a single unit. The collections framework is a unified architecture which is used to represent and manipulate collections. Theframework allows the collections to get manipulated independently as well as reduces

    programming effort for increasing performance.It includes implementations of interfaces, and algorithms included in it to manipulatethem. Basically it is a unified architecture that consists the following collections:

    Implementations are the reusable data objects used to store collections, which implementthe collection interfaces. Implementations are also responsible for documenting theoperations which they support. All of the general-purpose implementations of the Java

    platform support all of the optional operations.

    The following kinds of implementations are described below:

    http://www.roseindia.net/java/jdk6/Collection-algorithms.shtmlhttp://www.roseindia.net/java/jdk6/index.shtmlhttp://www.roseindia.net/java/jdk6/map-interface.shtml
  • 8/8/2019 Introduction to Collections API

    15/51

    General-purpose implementations: These are the most commonly usedimplementations, designed for performing all optional operations containedwithin the defined interfaces. They are summarized in the table below.

    Interfaces Implementations

    Hash table Tree Linked list Hash table +Linked listSet HashSet TreeSet LinkedHashSetList LinkedList Queue Map HashMap TreeMap LinkedHashMap

    The Java Collections Framework provides several general-purpose

    implementations of the Set , List , and Map interfaces. Each of the general- purpose implementations provides all optional operations contained in itsinterface. All permit null elements, keys, and values.

    Special-purpose implementations: These are designed to use in specialsituations and display nonstandard performance characteristics, usage restrictions,or behavior.

    Concurrent implementations: These are designed to support high concurrency.These implementations are part of the java.util.concurrent package.

    Wrapper implementations: These are used in combination with other types of implementations.

    Convenience implementations: These are mini-implementations, typically madevia static factory methods, that provide convenient, efficient alternatives togeneral-purpose implementations for special collections.

    Abstract implementations: These are implementations that facilitate theconstruction of custom implementations.

    The following description describes the categories in which the Collection Framework interfaces are implemented.

    The Set implementations are grouped into general-purpose and special-purposeimplementations. List implementations are grouped into general-purpose and special-

    purpose implementations. Map implementations are grouped into general-purpose,special-purpose, and concurrent implementations. The Queue implementations aregrouped into general-purpose and concurrent implementations.

  • 8/8/2019 Introduction to Collections API

    16/51

    Introduction to Collection Algorithms

    Algorithms:

    The Collection s and Arrays classes, available as a part of the Collections Framework,support various algorithms. The Java platform provides great majority of the algorithmsto perform different kind of operations such as sorting and searching .

    I. Sorting Algorithm:

    The sort algorithm reorders a List such that its elements are in ascending order according

    to an ordering relationship. The sort operation uses a slightly optimized merge sortalgorithm which is fast and stable. TreeSet and TreeMap classes offers a sorted version of sets and maps, there is no sorted List collection implementation. Sorting of a List is donewith the sort( ) method.

    For example, the following program prints the arguments (the arguments, given throughcommand line) of a List in an alphabetical order.

    import java.util.*;

    public class SortDemo { public static void main(String[] args) {

    List list = Arrays.asList(args); Collections.sort(list); System.out.println(list); }}

    Output of this program:

    C:\nisha>java SortDemo this is acommandline argument[a, argument, commandline, is,this]

    C:\nisha>

    Download this program:

    Searching Algorithm :

    http://www.roseindia.net/java/jdk6/SortDemo.javahttp://www.roseindia.net/java/jdk6/custom-collection-implementation.shtmlhttp://www.roseindia.net/java/jdk6/index.shtmlhttp://www.roseindia.net/java/jdk6/Collection-implementation.shtmlhttp://www.roseindia.net/java/jdk6/SortDemo.java
  • 8/8/2019 Introduction to Collections API

    17/51

    Besides sorting, the Collections and Arrays classes provide a mechanism to search a Listor an array, as well as to find the first and last values within a Collection. ThebinarySearch algorithm searches for a specified element in a sorted List. This algorithmtakes a List and an element to search for the search key . This form assumes that the Listis sorted in ascending order according to the natural ordering of its elements.

    Before searching an element, the List must be sorted, Once you have sorted the List,using Collection.sort( ) method, you can perform a quickly binary search operationusing the overridden binarySearch ( ) method.

    For example, the following program prints the sorted arguments list (the arguments,given through command line) and then search the position of a specified key value.

    import java.util.*;

    public class SearchDemo { public static void main(String[] args) {

    try { List list = Arrays.asList(args); Collections.sort(list); System.out.println( "The sorted list is: " +list); int pos = Collections.binarySearch(list, list.get( 2 )); System.out.println( "The position of the searched element is : " +pos

    +" and the element is:" +list.get( 2 )); } catch (Exception e){}

    }}

    Output of this program:

    C:\nisha>java SearchDemo this is acommandline argumentThe sorted list is: [a, argument,commandline, is, this]The position of the searchedelement is : 2 and the elementis:commandline

    C:\nisha>

  • 8/8/2019 Introduction to Collections API

    18/51

    Custom Collection Implementations

    So far you have learnt about the Java built-in Collection Interfaces implementations.Apart from these, some times programmer need to implement their own collectionsclasses. The Java platform allows you to write your own implementation of a corecollection interface. It is easy to write your own implementation with the help of abstract implementations .

    Lets discuss, why we should make a custom implementation.

    Persistent : All of the built-in Collection implementations reside in main memoryand appears when the program exits. If you want a collection to be available for the next time when the program starts, you can implement a collection that isconcurrently accessible by multiple programs.

    High-performance, special-purpose : Many data structures take advantage of restricted usage to offer better performance that is possible with general-purposeimplementations. For instance, consider a List containing long runs of identicalelement values. The runs can be represented as a single object containing therepeated element. This example is interesting because it deals with two aspects of

    performance: It requires less space but more time than an ArrayList.

    High-performance, general-purpose : The Java Collections Framework'sdesigners have tried to provide the best general-purpose implementations for eachinterface, but many, new ones are invented every day for the High performance of an application.

    Convenience : Some times you want additional implementations that offersconveniences than those offered by the Java platform. For instance, you may needa List to represent a contiguous range of Integers.

    To write your own custom implementation is not difficult. Java supports the abstractimplementations to implement your own collection. Lets see the way of writing thecustom collection implementation.

    import java.util.*;

    class MyClass { public static List myList(Object[] a) { return new ArrayList(a); } } class ArrayList extends AbstractList implements java.io.Serializable {

    http://www.roseindia.net/java/jdk6/introduction-java6.shtmlhttp://www.roseindia.net/java/jdk6/index.shtmlhttp://www.roseindia.net/java/jdk6/Collection-algorithms.shtml
  • 8/8/2019 Introduction to Collections API

    19/51

    private Object[] x;

    ArrayList(Object[] array) { x = array; } public Object get( int index) { return x[index]; } public Object set( int index, Object element) { Object oldVal = x[index]; x[index] = element; return oldVal; } public int size() { return x.length; } } public class CustomImpl{ public static void main(String[] args) {

    try { String s[]={ "My" , "Custom" , "Implementation" }; Object o; int i= 0 ; MyClass a= new MyClass(); List lst=a.myList(s); System.out.println( "The list is: " +lst); ArrayList al= new ArrayList(s); o=al.get( 1 ); System.out.println( "The retrieved element is: " +o); String s1= "Collection" ; o=al.set( 2 ,s1); System.out.println( "The set element in place of Implementation is: " +s1);

    System.out.println( "Now the new list is: " +lst); i=al.size(); System.out.println( "The size of the array list is: " +i); } catch (Exception e){} } }

    Output of the Program:

    C:\nisha>javac

    CustomImpl.java

    C:\nisha>javaCustomImplThe list is: [My, Custom,Implementation]The retrieved element is:Custom

  • 8/8/2019 Introduction to Collections API

    20/51

    The set element in placeof Implementation is:Collection

    Now the new list is:[My, Custom,

    Collection]The size of the array listis: 3

    C:\nisha>

    Description of the Program:

    In the given program, a custom implementation of Arrays.myList is defined which callsthe constructor of ArrayList class and pass the object to it. The get( ) and the set( )methods of the ArrayList class retrieve and set an element to the specified position of

    the List.

    Java 6.0 Collection Framework

    Some of the new collections APIs have been introduced in Java 6.0. These are:

    1. Deque: It is used to represent Double ended queue. With the help of thiscollection we can add or remove elements at both the ends. Dequeimplementation can be used as Stack ( Last in first out ) or Queue ( First in FirstOut ). There are two methods in Deque, which are used for insertion, retrieval andremoval of elements. One returns status or special value for each operation andthe other will throw exception if it fails in an operation.

    2. BlockingDeque: It is similar to Deque but with added functionality. When we tryto insert an element in a BlockingDeque and if the BlockingDeque is already fullthen the element can wait till the space becomes available to insert an element.There are four methods available for BlockingDeque.

    Methods throws exception Methods that times out (Waits for a given time for space to available) Methods that blocks (Waits indefinitely for space to available)

    http://www.roseindia.net/java/jdk6/collections-framework-enhancemen.shtmlhttp://www.roseindia.net/java/jdk6/index.shtmlhttp://www.roseindia.net/java/jdk6/custom-collection-implementation.shtml
  • 8/8/2019 Introduction to Collections API

    21/51

    Methods returns special value

    3. NavigableSet : It is used to return the closest matches of elements. For instance if we want retrieve the element, which is immediately greater than, or lower thanelement 20 or if we want to retrieve all elements greater than or lower than 35

    from sorted set elements [10,20,35,5] we can use NavigableSet methods that becomes just a method call. ConcurrentSkipListSet is one of the class thatimplements NavigableSet.

    4. NavigableMap: In NavigableSet, methods use to return values, but in NaviagableMap methods used to return the key,value pair.ConcurrentSkipListMap is the one of the class which implements

    NaviagableMap

    Some of the new Classes are:

    1. ArrayDeque: ArrayDeque is a class that implements Deque. If used as a stack or linked list, it performs much faster than before. It is neither thread safe nor hascapacity restrictions.

    2. LinkedBlockingDeque: It implements BlockingDeque. Maximum capacity can be specified by using BlockingDeque interface. However the maximum capacitywill be Integer.MAX_VALUE if not specified.

    3. ConcurrentSkipListSet: ConcurrentSkipListSet is one of the class thatimplements NavigableSet. It is used to return the closest matches of elements.

    4. ConcurrentSkipListMap: ConcurrentSkipListMap is the one of the classwhich implements NaviagableMap. In NavigableSet, methods use to returnvalues.

    5. AbstractMap.SimpleEntry: The key value pair of one single entry in a Map isheld by the instance of this class. Moreover it is a static nested class nested insideabstractMap class.

    6. AbstractMap.SimpleImmutableEntry: This class is similar toAbstractMap.SimpleEntry class however it has one difference that it throws theexception UnsupportedOperationException when we try to set a value while

    AbstractMap.SimpleEntry doesnt.

    Updated Classes in Java 6.0

    1. LinkedList 2. TreeSet

  • 8/8/2019 Introduction to Collections API

    22/51

    3. TreeMap 4. Collections

    Modified classes

    To implement the new interfaces we modify some classes like TreeSet is modified toimplement NavigableSet, LinkedList is modified to implement Deque, TreeMap ismodified to implement NavigableMap etc. Some of the new methods likenewSetFromMap and asLifoQueue have been added to Collections 2.

    Hence the bi- directional traversal has become easier with java6.0 collections. We caneven retrieve elements as desired.

    Collections Framework Enhancements

    In Collection framework, we are able to improve the performance hashing function that is

    used by java.util.HashMap . It provides some new Collection interfaces also.

    Following new Interfaces and Classes are provided in JAVA SE 6 :

    Deque Deque is a interface. It is a short for Double Ended Queue. Thisinterface defines some methods that access the element at both ends. That means

    by the methods of this interface we can add and remove the elements at both ends. ArrayDeque ArrayDeque Class implements a Deque interface. This class have

    no capacity restriction, it can grow according to usage. If the externalSynchronization is not available then it dont support concurrent access bymultiple thread.

    Constructors Details :

    public ArrayDeque()Above Constructor is used to make a empty array deque with an default capacitythat 16 elements.

    http://www.roseindia.net/java/jdk6/NavigableMapExample.shtmlhttp://www.roseindia.net/java/jdk6/index.shtmlhttp://www.roseindia.net/java/jdk6/introduction-java6.shtml
  • 8/8/2019 Introduction to Collections API

    23/51

    public ArrayDeque(int numElements)Above Construtor is used to make a empty array deque with the initial capacitythat is sufficient to hold the specified elements.

    public ArrayDeque()Etype is the type of the elements that held in this Collection. Above Constructor

    is used to make a array deque containing elements of specified type.

    Methods Details :

    void addFirst(Etype e)Above method is used to insert the element at the starting point of the array deque

    void addLast(Etype e)Above method is used to insert the element at the end point of the array deque.

    Above two methods throws following Exception:

    i. IllegalStateException Due to capacity restriction the element cannot be added.ii. ClassCastException Class of the specified element prevents it from beingadded to this deque

    iii. NullPointerException If specified element is null.iv. IllegalArgumentException If element having some property that prevent it

    from being added to this deque

    boolean offerFirst(Etype e)Above method is also used to insert the specified element at the starting point of the array deque. This method is preferable when we using a capacity restricteddeque. When element is added in array deque then its return true else it return

    false. boolean offerLast(Etype e)Above method is also used to insert the specified element at the end point of thearray deque. This method is preferable when we using a capacity restricted deque.When element is added in array deque then its return true else it return false.

    Above two methods throws following Exception:

    i. ClassCastException Class of the specified element prevents it from beingadded to this deque.

    ii. NullPointerException If specified element is null.

    iii. IllegalArgumentException If element having some property that prevent itfrom being added to this deque.

    Etype removeFirst()Above method is used to remove the first element of the array deque. And we canalso retrieve this element. But if array deque is empty then it throws a

    NoSuchElementException.

  • 8/8/2019 Introduction to Collections API

    24/51

  • 8/8/2019 Introduction to Collections API

    25/51

    }ArrayDeque dqname = new

    ArrayDeque();String name = null;name = c.readLine("Enter any

    String: ");dqname.add(name);show(dqname);

    name=c.readLine("Enter anystring to add on startingpoint of deque by addFirst():");

    dqname.addFirst(name);show(dqname);name=c.readLine("Enter any

    string to add on endingpoint of deque by addLast():");

    dqname.addLast(name);show(dqname);name=c.readLine("Enter any

    string to add on startingpoint of deque by offerfirst() :");

    dqname.offerFirst(name);show(dqname);name=c.readLine("Enter any

    string to add on endingpoint of deque by offerlast() :");

    dqname.offerLast(name);show(dqname);System.out.println("Getting the

    first elementby using getFirst()");

    String str1=dqname.getFirst();System.out.println("First

    element is : "+str1);System.out.println("Getting the

    Last element by usinggetLast()");

    str1=dqname.getLast();System.out.println("Last

    element is : "+str1);

    System.out.println("Getting thefirst element byusing peekFirst()");

    str1=dqname.peekFirst();System.out.println("First

    element is : "+str1);

    System.out.println("Getting theLast element by

    using peekLast()");str1=dqname.peekLast();System.out.println("Last

    element is : "+str1);System.out.println("Removing

    the first element

  • 8/8/2019 Introduction to Collections API

    26/51

    by using removeFirst()");str1=dqname.removeFirst();show(dqname);System.out.println("Removing

    the Last elementby using removeLast()");

    str1=dqname.removeLast();show(dqname);System.out.println("Removing

    the first elementby using pollFirst()");

    str1=dqname.pollFirst();show(dqname);System.out.println("Removing

    the Last elementby using pollFirst()");

    str1=dqname.pollLast();show(dqname);

    }static void

    show(ArrayDeque dqname){Iterator nameIter =

    dqname.iterator();while(nameIter.hasNext())

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

    }

    Output of the program is:

    C:\j2se6>javac NewDeque.java

    C:\j2se6>java NewDequeEnter any String: RoseRoseEnter any string to add on starting point of deque by addFirst():IndiaIndiaRoseEnter any string to add on ending point of deque by addLast():NetIndiaRoseNetEnter any string to add on starting point of deque by offerfirst() :ComComIndiaRoseNet

  • 8/8/2019 Introduction to Collections API

    27/51

    Enter any string to add on ending point of deque by offerlast() :ChandanComIndiaRose

    NetChandanGetting the first element by using getFirst()First element is : ComGetting the Last element by using getLast()Last element is : ChandanGetting the first element by usingpeekFirst()First element is : ComGetting the Last element by usingpeekLast()

    Last element is : ChandanRemoving the first element by usingremoveFirst()IndiaRoseNetChandanRemoving the Last element by usingremoveLast()IndiaRoseNetRemoving the first element by usingpollFirst()RoseNetRemoving the Last element by usingpollFirst()Rose

    C:\j2se6>

  • 8/8/2019 Introduction to Collections API

    28/51

    Navigable Map Example

    We already know that NavigableMap is similar to NavigableSet . In NavigableMap we

    use methods to return the key value pair like navMap.put(1, "January"); whereas in NavigableSet we use methods to return values. ConcurrentSkipListMap is the one of the class which implements NavigableMap. Lets have a look at the example.

    Description of program:

    The following program helps you in inserting, removing and retrieving the data from theNavigableMap . It uses the put() method to add the element. If you want to retrieve thedata at first and last position from the NavigableMap, you use the firstEntry() andlastEntry() methods. The descendingMap() method represents all data to the

    NavigableMap in descending order.

    You can retrieve the nearest less than or equal to the given number and the greatest keystrictly less than the given number floorEntry() and lowerEntry() methods. And youretrieve a key-value associated with the least key strictly greater than the given key, youuse the higherEntry() method. The pollFirstEntry() method removes the first data fromthe NavigableMap and pollLastEntry() method also removes the data at the last positionfrom the NavigableMap.

    Here is the code of program:

    import java.util.*;import java.util.concurrent.*;

    public class NavigableMapExample{ public static void main(String[] args) { System.out.println( "Navigable Map Example!\n" ); NavigableMap navMap = new

    ConcurrentSkipListMap(); navMap.put( 1 , "January" ); navMap.put( 2 , "February" ); navMap.put( 3 , "March" );

    http://www.roseindia.net/java/jdk6/NavigableSetExample.shtmlhttp://www.roseindia.net/java/jdk6/index.shtmlhttp://www.roseindia.net/java/jdk6/collections-framework-enhancemen.shtml
  • 8/8/2019 Introduction to Collections API

    29/51

    navMap.put( 4 , "April" ); navMap.put( 5 , "May" ); navMap.put( 6 , "June" ); navMap.put( 7 , "July" ); navMap.put( 8 , "August" ); navMap.put( 9 , "September" ); navMap.put( 10 , "October" ); navMap.put( 11 , "November" ); navMap.put( 12 , "December" ); //Displaying all data System.out.println( "Data in the navigable map: " +

    navMap.descendingMap()+ "\n" ); //Retrieving first data System.out.print( "First data: " + navMap.firstEntry()+ "\n" ); //Retrieving last data System.out.print( "Last data: " + navMap.lastEntry()+ "\n\n" ); //Retrieving the nreatest less than or equal to the given key System.out.print( "Nearest less than or equal to the given key: "

    + navMap.floorEntry( 5 )+ "\n" ); //Retrieving the greatest key strictly less than the given key

    System.out.println( "Retrieving the greatest key strictly less thanthe given key: " + navMap.lowerEntry( 3 ));

    //Retrieving a key-value associated with the least keystrictly greater than the given key

    System.out.println( "Retriving data from navigable map greter thanthe given key: " + navMap.higherEntry( 5 )+ "\n" );

    //Removing first System.out.println( "Removing First: " + navMap.pollFirstEntry()); //Removing last System.out.println( "Removing Last: " + navMap.pollLastEntry()+ "\n" ); //Displaying all data System.out.println( "Now data: " + navMap.descendingMap()); }

    }

    Download this example.

    Output of program:

    C:\vinod\collection>javac NavigableMapExample.java

    C:\vinod\collection>java NavigableMapExample Navigable Map Example!

    Data in the navigable map: {12=December,11=November, 10=October, 9=September, 8=August, 7=July, 6=June, 5=May, 4=April,3=March, 2=February, 1=January}

    First data: 1=JanuaryLast data: 12=December

    http://www.roseindia.net/java/jdk6/NavigableMapExample.javahttp://www.roseindia.net/java/jdk6/NavigableMapExample.java
  • 8/8/2019 Introduction to Collections API

    30/51

    Nearest less than or equal to the given key: 5=MayRetrieving the greatest key strictly less than thegiven key: 2=FebruaryRetriving data from navigable map greter than the

    given key: 6=June

    Removing First: 1=JanuaryRemoving Last: 12=December

    Now data: {11=November, 10=October,9=September, 8=August, 7=July, 6=June, 5=May, 4=April, 3=March, 2=February}

    C:\vinod\collection>

    Navigable Set Example

    In the example below we have used NavigableSet method to sort the elements inascending order, descending order, also to retrieve the element which is immediatelygreater than or equal to 35 etc. With the help of NavigableSet methods its just a methodcall to get the result. It is used to return the closest matches of elements for the givenelements in the collection.

    Description of program:

    Inserting the data in the NavigableSet by the add() method. The NavigableSet providesthe facility to getting the data in both orders: ascending and descending orders. The

    descendingSet() method returns the data from the NavigableSet in descending order. If you want to get the data in ascending order must be used an iterator. An iterator stores thedata as a index and the hasNext() method returns ' true ' until, the next() method returnsthe element in ascending order.

    Here, you remove the element from the NavigableSet at first and last position, you usethe pollFirst() and pollLast() methods. Sometimes, you want to get the less and greater than or equal to the given element by using the floor() and ceiling() methods. For getting

    http://www.roseindia.net/java/jdk6/CollectionTest.shtmlhttp://www.roseindia.net/java/jdk6/index.shtmlhttp://www.roseindia.net/java/jdk6/NavigableMapExample.shtml
  • 8/8/2019 Introduction to Collections API

    31/51

    the all elements of the NavigableSet that is greater than or equal to the given element bythe tailSet() method and less than or equal to the given element of the NavigableSet bythe headSet() method.

    Here is the code of program:

    import java.util.*;import java.util.concurrent.*;

    public class NavigableSetExample{ public static void main(String[] args) { System.out.println( "Navigable set Example!\n" ); NavigableSet nSet = new ConcurrentSkipListSet(); nSet.add( 10 ); nSet.add( 20 ); nSet.add( 50 ); nSet.add( 30 ); nSet.add( 100 ); nSet.add( 80 ); // Returns an iterator over the elements in navigable set,

    in ascending order. Iterator iterator = nSet.iterator(); System.out.print( "Ascending order navigable set: " ); //Ascending order list while (iterator.hasNext()){ System.out.print(iterator.next() + " " ); } System.out.println(); //Descending order list System.out.println( "Descending order navigable set: " +

    nSet.descendingSet() + "\n" ); //Greater than or equal to the given element

    System.out.println( "Least element in Navigable set greater thanor equal to 35: " + nSet.ceiling( 35 ));

    //Less than or equal to the given element System.out.println( "Greatest element in Navigable set less than

    or equal to 35: " + nSet.floor( 35 ) + "\n" ); //Viewing the portion of navigable set whose elements are

    strictly less than the given element System.out.println( "Navigable set whose elements are strictly

    less than '40': " + nSet.headSet( 40 )); //Viewing the portion of navigable set whose elements are

    greater than or equal to the given element System.out.println( "Navigable set whose elements are greater

    than or equal to '40': " + nSet.tailSet( 40 ) + "\n" ); //Removing first element from navigable set System.out.println( "Remove element: " +nSet.pollFirst()); //After removing the first element, now get navigable set System.out.println( "Now navigable set: " + nSet.descendingSet() + "\n" ); //Removing last element from navigable set System.out.println( "Remove element: " + nSet.pollLast()); //After removing the last element, now get navigable set System.out.println( "Now navigable set: " + nSet.descendingSet()); }}

  • 8/8/2019 Introduction to Collections API

    32/51

  • 8/8/2019 Introduction to Collections API

    33/51

  • 8/8/2019 Introduction to Collections API

    34/51

    if (collection.isEmpty()){ System.out.println( "Collection is empty" ); } else { System.out.println( "Collection size: " + size); } System.out.println(); // Remove specific data

    collection.remove(str2); System.out.println( "After removing [" + str2 + "]\n" ); System.out.print( "Now collection data: " ); iterator = collection.iterator();

    while (iterator.hasNext()){ System.out.print(iterator.next() + " " );

    } System.out.println(); size = collection.size(); System.out.println( "Collection size: " + size + "\n" ); //Collection empty collection.clear();

    size = collection.size(); if (collection.isEmpty()){ System.out.println( "Collection is empty" ); } else { System.out.println( "Collection size: " + size); } }}

    Download this example.

    Output of this program:

    C:\vinod\collection>javacCollectionTest.java

    C:\vinod\collection>javaCollectionTestCollection Example!

    Collection data: BlueWhite Green Yellow

    Collection size: 4

    After removing [White]

    Now collection data:Blue Green YellowCollection size: 3

    http://www.roseindia.net/java/jdk6/CollectionTest.javahttp://www.roseindia.net/java/jdk6/CollectionTest.java
  • 8/8/2019 Introduction to Collections API

    35/51

    Collection is empty

    C:\vinod\collection>

    Linked List Example

    This section discusses an example to demonstrate the various methods of List interface.We are using two classes ArrayList and LinkedList in the example code. The code

    below is similar to the previous example, but it performs many List operations . Lets

    discuss the example code.

    Description of program:

    This program helps you in storing the large amount of data as a collection. TheLinkedList is a part of collection that constructs a list containing the elements of thespecified collection. Iterator methods returns the values in the order in which they arestored.

    If you want to insert the data in the linkedList then use add() method. The hasNext()method returns true if the iterator contains more elements and the next() method returns

    the next element in the iteration. To insert and remove the data at first, last and specified position in the linkedList , you use the addFirst() , addLast() , add() , removeFirst() ,removeLast() and remove() methods. To retrieve the element with respect to a specified

    position use the getFirst() , getLast() and get() methods.

    Here is the code of program:

    import java.util.*;

    public class LinkedListExample{ 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); list.add(num4); size = list.size();

    http://www.roseindia.net/java/jdk6/TreeMapExample.shtmlhttp://www.roseindia.net/java/jdk6/index.shtmlhttp://www.roseindia.net/java/jdk6/CollectionTest.shtml
  • 8/8/2019 Introduction to Collections API

    36/51

    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: " ); 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

  • 8/8/2019 Introduction to Collections API

    37/51

    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 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); } }}

    Download this example.

    Output of program:

    C:\vinod\collection>javacLinkedListExample.java

    C:\vinod\collection>javaLinkedListExampleLinked List Example!Linked list data: 11 22 33 44Linked list size: 4Adding data at 1st location:55

    Now the list contain: 55 11

    http://www.roseindia.net/java/jdk6/LinkedListExample.javahttp://www.roseindia.net/java/jdk6/LinkedListExample.java
  • 8/8/2019 Introduction to Collections API

    38/51

    22 33 44 Now the size of list: 5Adding data at last location:66

    Now the list contain: 55 11

    22 33 44 66 Now the size of list: 6Adding data at 3rd location:55

    Now the list contain: 55 1199 22 33 44 66

    Now the size of list: 7First data: 55Last data: 66Data at 4th position: 22Data removed from 1st

    location: 55 Now the list contain: 11 9922 33 44 66

    Now the size of list: 6Data removed from lastlocation: 66

    Now the list contain: 11 9922 33 44

    Now the size of list: 5Data removed from 2ndlocation: 99

    Now the list contain: 11 2233 44

    Now the size of list: 4Linked list is empty

    C:\vinod\collection>

    Tree Map Example

  • 8/8/2019 Introduction to Collections API

    39/51

    In the following example, we have used the TreeMap method, which stores its elementsin a tree and orders its elements based on their values. Here in the example we have usedthe key of the element to show the values of the element. To retrieve the keys and values

    use keySet() and values() method respectively.

    This program shows the data elements left after removing the particular element byspecifying its key. Using the Iterator interface methods, we can traverse a collection fromstart to finish and safely remove elements from the underlying Collection.

    Here is the code of program:

    import java.util.*;

    public class TreeMapExample{ public static void main(String[] args) {

    System.out.println( "Tree Map Example!\n" ); TreeMap tMap = new TreeMap(); //Addding data to a tree map tMap.put( 1 , "Sunday" ); tMap.put( 2 , "Monday" ); tMap.put( 3 , "Tuesday" ); tMap.put( 4 , "Wednesday" ); tMap.put( 5 , "Thursday" ); tMap.put( 6 , "Friday" ); tMap.put( 7 , "Saturday" ); //Rerieving all keys System.out.println( "Keys of tree map: " + tMap.keySet()); //Rerieving all values System.out.println( "Values of tree map: " + tMap.values()); //Rerieving the value from key with key number 5 System.out.println( "Key: 5 value: " + tMap.get( 5 )+ "\n" ); //Rerieving the First key and its value System.out.println( "First key: " + tMap.firstKey() + " Value: "

    + tMap.get(tMap.firstKey()) + "\n" ); //Rerieving the Last key and value System.out.println( "Last key: " + tMap.lastKey() + " Value: "

    + tMap.get(tMap.lastKey()) + "\n" ); //Removing the first key and value System.out.println( "Removing first data: " + tMap.remove(tMap.firstKey())); System.out.println( "Now the tree map Keys: " + tMap.keySet()); System.out.println( "Now the tree map contain: " + tMap.values() + "\n" ); //Removing the last key and value System.out.println( "Removing last data: " + tMap.remove(tMap.lastKey())); System.out.println( "Now the tree map Keys: " + tMap.keySet()); System.out.println( "Now the tree map contain: " + tMap.values()); }}

    Download this example.

    http://www.roseindia.net/java/jdk6/TreeMapExample.javahttp://www.roseindia.net/java/jdk6/TreeSetExample.shtmlhttp://www.roseindia.net/java/jdk6/index.shtmlhttp://www.roseindia.net/java/jdk6/LinkedListExample.shtmlhttp://www.roseindia.net/java/jdk6/TreeMapExample.java
  • 8/8/2019 Introduction to Collections API

    40/51

    Output of this program:

    C:\vinod\collection>javac TreeMapExample.java

    C:\vinod\collection>java TreeMapExample

    Tree Map Example!

    Keys of tree map: [1, 2, 3, 4, 5, 6, 7]Values of tree map: [Sunday, Monday, Tuesday,Wednesday, Thursday, Friday, Saturday]Key: 5 value: Thursday

    First key: 1 Value: Sunday

    Last key: 7 Value: Saturday

    Removing first data: Sunday Now the tree map Keys: [2, 3, 4, 5, 6, 7] Now the tree map contain: [Monday, Tuesday,Wednesday, Thursday, Friday, Saturday]

    Removing last data: Saturday Now the tree map Keys: [2, 3, 4, 5, 6] Now the tree map contain: [Monday, Tuesday,Wednesday, Thursday, Friday]

    C:\vinod\collection>

    Tree Set Example

    In the following example, we have used the TreeSet collection, which is similar toTreeMap that stores its elements in a tree and maintain order of its elements based ontheir values. To get the size of TreeSet collection size() method is used. Our TreeSetcollection contains 4 elements and the size of the TreeSet can be determine by callingsize() method.

    http://www.roseindia.net/java/jdk6/changes-in-jar-and-zip.shtmlhttp://www.roseindia.net/java/jdk6/index.shtmlhttp://www.roseindia.net/java/jdk6/TreeMapExample.shtml
  • 8/8/2019 Introduction to Collections API

    41/51

    Similarly, we have used first() and last() to retrieve first and last element present in theTreeSet. Program also shows the method to remove the element and then display theremaining elements. To remove all data from the TreeSet, use the clear() method. Todetermine whether TreeSet is empty or not use isEmpty() method. If the TreeSet isempty, it displays the message " Tree set is empty ." otherwise it displays the size of

    TreeSet.

    Here is the code of program:

    import java.util.*;

    public class TreeSetExample{ public static void main(String[] args) { System.out.println( "Tree Set Example!\n" ); TreeSet tree = new TreeSet(); tree.add( 12 ); tree.add( 23 ); tree.add( 34 );

    tree.add( 45 ); Iterator 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 impty 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( 30 )){ 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();

  • 8/8/2019 Introduction to Collections API

    42/51

    if (tree.isEmpty()){ System.out.print( "Tree Set is empty." ); } else { System.out.println( "Tree Set size: " + tree.size()); } }}

    Download this example.

    Output of this program:

    C:\vinod\collection>javacTreeSetExample.java

    C:\vinod\collection>java

    TreeSetExampleTree Set Example!

    Tree set data: 12 23 34 45Tree Set size: 4First data: 12Last data: 45Data doesn't exist!

    Now the tree set contain: 1223 34 45

    Now the size of tree set: 4Tree Set is empty.

    C:\vinod\collection>

    Changes in Jar and Zip

    In Java SE 6 there are two changes in jar command behavior:

    Before Java SE 6, the timestamps (date and time) of extracted files by jar command are those listed the current time means extraction time instead of

    http://www.roseindia.net/java/jdk6/TreeSetExample.javahttp://www.roseindia.net/java/jdk6/java-web-start.shtmlhttp://www.roseindia.net/java/jdk6/index.shtmlhttp://www.roseindia.net/java/jdk6/TreeSetExample.shtmlhttp://www.roseindia.net/java/jdk6/TreeSetExample.java
  • 8/8/2019 Introduction to Collections API

    43/51

    archive file time. But other de/compression tools use the archive time. So in JavaSE 6, they do a change in jar command behavior that is the date and time of extracted files by jar command were the archive time. But if the old behavior isneeded, use sun.tools.jar.useExtractionTime= true

    At the time of creating a jar, we have the ability in executable jar file to specify

    the entry point for stand-alone application bundle. The 'e' option declare the entry point through creating or overriding the Main-Class attribute value in the jar file'smanifest.

    There are some changes in ZIP File also:

    Number of open ZIP files - Prior to Java SE 6, we faced the limitation on thenumber of concurrently open ZIP files in Microsoft Windows. And the maximumused to be 2306 but now this limitation has removed and the maximum used isdepend on the whatever the platform will support.

    Number of entries in a ZIP file - The ZIP file format was using 2-byte field to

    record the number of entries in the file, imposing a 64K limit. But in Java SE 6,ignores that field, just counts the entries. Before Java 6 you could count theentries with ZipInputStream or ZipFile , but if there were more than 64 entries inthe file you get the different result.

    ZIP File Names - Java SE 6 support the file names longer than 256 characters. API Changes - There are two new compressed streams have been added :

    1. java.util.zip.DeflaterInputStream - This stream is used to read the compresseddata. For example, This stream can be useful if any client want to send the data incompressed form over a network and it can compressed into packets byDeflaterInputStream.

    2. java.util.zip.InflaterOutputStream - This stream is used to write the decompresseddata. For example, At the receiving end decompresses the compressed packet bywriting to an InflaterOutputStream.

    Java Web Start Enhancements in version6

    http://www.roseindia.net/java/jdk6/enhancements-in-networking-features.shtmlhttp://www.roseindia.net/java/jdk6/index.shtmlhttp://www.roseindia.net/java/jdk6/changes-in-jar-and-zip.shtml
  • 8/8/2019 Introduction to Collections API

    44/51

    Enhancements in Java Web Start

    JNLP Specification addition of the element - The elementwith its attributes "policy" and "check" is now supported. It describes theapplications preferences for how Java Web Start should check for updates on the

    web, and what to do when it is known before starting the application that there isan update available. Prior to Java SE 6, In Java Web Start element was overloadedfor two things. First, the application can run in offline mode. Second, Try to check for updates before running an application (when not run in offline mode) couldtime out. When a times out, the application would launched to the cache wile andthe updates check continued in the background. In Java SE 6, the "policy" attribute of element is used to determine whatto do when it is known before launching the application that an update is

    available. The values of policy attribute can be "always" (default value), "prompt-update" or "prompt-run". Because of "check" attribute of element inversion 6, the element has no more its second meaning thatdiscussed above. Default values : has same behavior was specified by in previous version. Whenever was previously used, for that behavior you need to specify . A can be specified to alwaysimmediately launch from the cache while spawning a check for update in the

    background.

    JNLP Specification relaxation is required for the DownloadService API -

    Upto now we used to pass the URLs as arguments to all APIs were restricted to beused a URLs to resources listed in the jnlp files. In this version there is not anysuch restrictions for signed and trusted code there is no restriction on untrustedcode that it has to be listed in the jnlp files but the only requirement is that itshould be from the same codebase.

    But in current version, URLs to jnlp files are allowed, so that by usingDownloadService.removeResource() you can remove a whole application fromcache and by using DownloadService.load Resource() you can import anapplication. Due to this change now resources is not listed in jnlp file can now beused in an application.

    SocketService Implementation - A clarification in the definition of the sandboxis also a another important specification change, that is only the default sandbox,this implementation is free to prompt the user to allow actions that are not allowed

    by the sandbox. In Java 1.5, it was done for printing, so that in AWT by using printing API, you can expand the sandbox for allowing the application to accessthe printer. But in Java SE 6, it is done for socket connection, that's why if anuntrusted application try to connect to a url, the user can be prompted to allow the

  • 8/8/2019 Introduction to Collections API

    45/51

    connection.

    Replace element by new element in JNLP file - This elementwill be used only with Java Web Start version 6 for jnlp files. The elementis replaced by tag (The main reason of behind that is only the Java

    Platform Standard Edition is no longer known as j2se). Enhanced element now contain the and

    sub-elements - When creating file extension and mime type associations withJava Web Start application, you can specify description and a separate icon to beused for each association.

    JNLP is now an instance of the URLClassLoader - It gives some powerfuladvantages. First, Jar indexing is now fully supported. If you want to create a jar index of several jar file in the main jar file that indexes all the jar files, and thenyou can mark each additional jar as lazy, and it can be download only when a

    resource or class in it is referenced. Second, The JNLPClassLoader was rewrittento extend URLClassLoader. For getting a list of jar elements that are listed in the jnlp files an application can invoke getURLs(). The URL returned for calls toClass Loader.getResource() is proper Jar URL of the item on the net. Byextending URLClassLoader, it allows Java Web Start to operate without caching.

    Java Web Start now supports icon formats - Now, two icon formats "png","ico" are supported by Java Web Start. This enhancement allows to specify anicon that would not be translated into a different format depending on its use.

    Now you can specify a icon format kind="shortcut" with width and heightattributes. Example - . For destktop shortcuts use the icon size is closer to 32x 32 and for menu shortcut its closer to 16 x 16.

    Add/Remove entries will now supported on Windows for Java Web Start -Add/Remove entries will now include will now include the publisher, install date,

    publisher websight and application icon from the jnlp file information block.

    Desktop shortcut tooltips - Java Web Start creates a Desktop shortcuts. In Jnlpfile Java Web Start will use the element to create a tooltip for describing the application.

    Enhanced JNLPDownloadServlet - Now, the enhanced JNLPDownloadServletcontains the two macro $$hostname and a $$sight. The expanded $$hostnamecontains the host name and $$sight contains the web site address without theWAR context portion.

    The safe vm args and properties list has been enhanced and some Command LineInterface (CLI) items are also changed or added.

  • 8/8/2019 Introduction to Collections API

    46/51

    Java Web Start and Java Plug-in Common Enhancements

    Cache and System FormatIn Java SE 6, the cache format has been fully changed. That's why, any existingcode using previous format of cache for Java Web Start or Java Plug-in will no

    longer work. Existing applications cache will be upgraded and converted to thenew format of cache when the first time you launch a Java Web Start application,or by launching the cache viewer using javaws-viewer. And System cache willupgraded when the first time you run Java Web Start application in system mode,or just launching javaws - system.

    Download Engine and Cache ConsolidationDownload Engine and entire caching mechanism are redesigned and consolidated

    between Java Web Start and Java Plug-in. This include some new features in JavaWeb Start:

    o By using Java Control Panel it allow to disable the caching.

    o The maximum cache size set in Java Control Panel is supported in JavaWeb Start. o A cleanup thread can be started by Java Web Start to removed Least

    Recently Used (LRU) items from the cache when approaching themaximum size.

    o The directive is now supported. When using this directive,and update check is made to verify the cached contents is same as at theURL.

    o The expiration-date is supported. If any download resource contains anexpiration date, it will not be used after that date.

    Secure VersioningIn Java SE 6, signed Java Web Start applications are not affected but the unsignedJava Web Start applications specify a version trigger a security warning, requiringexplicit user permission before running the application.

    Other Enhancements o All dialogs and screens have been redesigned by user experience team to

    be more user friendly and accessible. o Now, Java Console is not included in modality. In Java 6, some new

    features are added in modality by AWT. By this you can interact with JavaConsole even when the application is displaying a modal dialog.

    o CRL (Certificate Revocation Lists) and OCSP (Online Certificate StatusProtocol) are supported by Java Web Start and Java Plug-in for verifyingthe certificates.

    o SSL/TSL are supported by Java Web Start and Java Plug-in. An optionhas been provided by Java Control Panel to select the default SSLhandshaking protocol. The default is set to SSLv3 and SSLv2, but thenuser can change it to TSL.

  • 8/8/2019 Introduction to Collections API

    47/51

    Enhancements in Networking Features

    Changes in NetworkInterface Class

    NetworkInterface is a class in java.net package. This class is used to represent a Network Interface and it is made up of a name and a IP addresses list assigned to this interface. InJava 6, this class provides some new methods for accessing state and configurationinformation and this information is related to system's network adapters. This includes

    information like broadcast address, list object with all or a subset of the InterfaceAddress,enumeration object with all of the subinterfaces, subnet mask, hardware address (MACaddresses) and MTU size.

    Some new methods are added in NetworkInterface class are as follows:

    public boolean isUp()Above method returns true if the network interface is up and running. Upspecifies that routing entries have been set up for the network interface. Andrunning specifies that required system resources have been allocated.

    public boolean isLoopback()

    Above method returns true if the network interface is a loopback interface. public boolean isPointToPoint()Above method returns true if the network interface is point to point interface.

    public boolean supportsMulticast()Above method is used to know the network interface is support multicasting or not. If yes then its return true.

    public byte[] getHardwareAddress()Above method is used to get the byte array of MAC address. It return null if theaddress is not accessible or doesn't exist.

    public int getMTU()Above method returns the value of MTU (Maximum Transmission Unit) of this

    interface.Above all methods throws an SocketException if an I/O error occurs.

    public boolean isVirtual()Above method return true if the network interface is virtual interface. Virtualinterfaces are those interfaces that created as child of physical interface and givendifferent settings such as MTU or address.

    http://www.roseindia.net/java/jdk6/index.shtmlhttp://www.roseindia.net/java/jdk6/index.shtmlhttp://www.roseindia.net/java/jdk6/java-web-start.shtml
  • 8/8/2019 Introduction to Collections API

    48/51

    public List getInterfaceAddresses()Above method is used to get a list object of all or a subset of theInterfaceAddresses of this network interface. If security manager is available, itinvoke its checkConnect() for each InterfaceAddress with the InetAddress. Onlythose InterfaceAddresses will be returned in the list where the checkConnect()

    doesn't throw a SecurityException. public Enumeration getSubInterfaces()Above method is used to get an enumeration object with all of the virtualinterfaces (subinterfaces) of this network interface.

    public NetworkInterface getParent()Above method is used to get the parent NetworkInterface of this network interface

    but only when if it is a subinterface. It returns null if it has no parent or it is a physical interface.

    InterfaceAddress Class

    A new class InterfaceAddress is also included in java.net package. This class is used torepresent a Network Interface address. And its encapsulates all information about a NetworkInterface's IP addresses including the subnet mask and broadcast address.

    Following methods are included in this class:

    public InetAddress getAddress()Above method returns an InetAddress of the given Interface Address.

    public InetAddress getBroadcast()Above method returns an InetAddress representing the broadcast address for thisinterface address. It returns null if there is no broadcast address. Only IPv4

    networks have broadcast address. public short getNetworkPrefixLength()Above method returns the network Prefix length for the subnet mask of theinterface address.

    The following example demonstrates the above methods:

    import java.util.*;import java.net.*;public class NetInt{

    public static void main(Stringargs[])throws SocketException

    {Enumeration netis=

    NetworkInterface.getNetworkInterfaces();while(netis.hasMoreElements()){NetworkInterface nis=netis.nextElement();System.out.println("Network Interface

    name is :"

  • 8/8/2019 Introduction to Collections API

    49/51

    +nis.getName());System.out.println("Display name of

    network interface is :"

    +nis.getDisplayName());System.out.println("Network Interface is

    up and running :"

    +nis.isUp());System.out.println("Network Interface is

    loopback :"

    +nis.isLoopback());System.out.println("Network Interface is

    point topoint

    interface :"+nis.isPointToPoint());System.out.println("Network Interface

    support multicasting :"

    +nis.supportsMulticast());System.out.println("Network Interface MTU

    value is :"

    +nis.getMTU());System.out.println("Network Interface is

    virtual interface :"

    +nis.isVirtual());System.out.println("Network Interface has

    any Paren :"

    +nis.getParent());byte[] haddress=nis.getHardwareAddress();if (haddress!= null){System.out.print (" Hardware address =

    ");for (int i = 0; i < haddress.length; i++)System.out.printf ("%02X%c", haddress

    [i],(i != haddress.length-1) ?

    '-' :'\0');System.out.println();

    }

    Listiaddress=nis.getInterfaceAddresses();

    Iteratoriiaddress=iaddress.iterator();

    while(iiaddress.hasNext()){InterfaceAddress iadd=iiaddress.next();System.out.println("Interface Address

    -");System.out.println("InetAddress of the

  • 8/8/2019 Introduction to Collections API

    50/51

  • 8/8/2019 Introduction to Collections API

    51/51

    Network Interface has any Paren :nullHardware address = 00-B0-D0-3A-71-F7Interface Address -InetAddress of the InterfaceAddress :/192.168.10.55

    Broadcast Addres of the InterfaceAddress :/192.168.10.255Network Prefix Length of the Interface Address :24

    C:\j2se6>