Collections Frame Work in Java

Collections Frame Work in Java

The detailed information which providing below information is enough with respect to Collection frame work

Q)        

Collection classes

Collection Interfaces

Legacy classes

Legacy interface

Abstract collection

Collection

Dictionary

Enumerator

Abstract List

List

Hash Table

 

Abstract Set

Set

Stack

 

Array List

Sorted Set

Vector

 

Linked List

Map

Properties

 

Hash set

Iterator

 

 

Tree Set

 

 

 

Hash Map

 

 

 

Tree Map

 

 

 

Abstract Sequential List

 

 

 

           Collection Classes

       Abstract collection - Implements most of the collection interfaces.

           Abstract List - Extends Abstract collection & Implements List Interface. A.L allow “random access”.

 Methods>> void add (int index, Object element), boolean add(Object o), boolean addAll(Collection c), boolean addAll(int index, Collection c), Object remove(int index), void clear(), Iterator iterator().

       Abstract Set - Extends Abstract collection & Implements Set interface.

 Array List - Array List extends AbstractList and implements the List interface. ArrayList is a variable length    of array of object references, ArrayList support dynamic array that grow as needed. A.L allow rapid random access to element but slow for insertion and deletion from the middle of the list. It will allow duplicate elements. Searching is very faster.

A.L internal node traversal from the start to the end of the collection is significantly faster than Linked List traversal.

      - A.L is a replacement for Vector.

    Methods>>void add (int index, Object element), boolean add(Object o), boolean addAll(Collection c), boolean addAll(int index, Collection c), Object remove(int index), void clear(), object get(int index), int indexOf(Object element),  int latIndexOf(Object element), int size(), Object [] toArray(). 

 Linked List - Extends AbstactSequentialList and implements List interface. L.L provide optimal sequence access, in expensive insertion and deletion from the middle of the list, relatively slow for random access. When ever there is a lot of insertion & deletion we have to go for L.L. L.L is accessed via a reference to the first node of the list. Each subsequent node is accessed via a reference to the first node of the list. Each subsequent node is accessed via the link-reference number stored in the previous node.

     Methods>> void addFirst(Object obj), addLast(Object obj), Object getFirst(), Object getLast(),void add (int index, Object element), boolean add(Object o), boolean addAll(Collection c), boolean addAll(int index, Collection c), Object remove(int index), Object remove(Object o), void clear(), object get(int index), int indexOf(Object element), int latIndexOf(Object element), int size(), Object [] toArray(). 

 Hash Set - Extends AbstractSet & Implements Set interface, it creates a collection that uses HashTable for storage, H.S does not guarantee the order of its elements, if u need storage go for TreeSet. It will not allow duplicate elements

    Methods>>boolean add(Object o), Iterator iterator(), boolean remove(Object o), int size().

 Tree Set - Extends Abstract Set & Implements Set interface. Objects are stored in sorted, ascending order. Access and retrial times are quite fast. It will not allow duplicate elements

     Methods>> boolean add(Object o), boolean addAll(Collection c), Object first(), Object last(), Iterator iterator(), boolean remove(Object o).

 Hash Map - Extends Abstract Map and implements Map interface. H.M does not guarantee the order of elements, so the order in which the elements are added to a H.M is not necessary the order in which they are ready by the iterate. H.M permits only one null values in it while H.T does not

 - HashMap is similar to Hashtable.

     Tree Map - implements Map interface, a TreeMap provides an efficient means of storing key/value pairs in sorted order and allow rapid retrieval.

          Abstract Sequential List à Extends Abstract collection; use sequential access of its elements.

 Collection Interfaces    

      Collection - Collection is a group of objects, collection does not allow duplicate elements.

     Methods >> boolean add(Object obj), boolean addAll(c), int Size(), Object[] toArray(), Boolean isEmpty(), Object [] toArray(), void clear().Collection c), Iterator iterator(),

boolean remove(Object obj), boolean removeAll(Collection

      Exceptions >> UnSupportedPointerException, ClassCastException.

 List  - List will extend Collection Interface, list stores a sequence of elements that can contain duplicates, elements can be accessed their position in the list using a zero based index, (it can access objects by index)

Methods >> void add(int index, Object obj), boolean addAll(int index, Collection c), Object get(int index), int indexOf(Object obj), int lastIndexOf(Object obj), ListIterator  iterator(), Object remove(int index), Object removeAll(Collection c), Object set(int index, Object obj).

Set  - Set will extend Collection Interface, Set cannot contain duplicate elements. Set stored elements in an unordered way. (it can access objects by value).

          Sorted Set  - Extends Set to handle sorted sets, Sorted Set elements will be in ascending order.

      Methods >> Object last(), Object first(), compactor compactor().

      Exceptions >> NullPointerException, ClassCastException, NoSuchElementException.

       Map - Map maps unique key to value in a map for every key there is a corresponding value and you will lookup the values using keys. Map cannot contain duplicate “key” and “value”. In map both the “key” &  valueare objects.

     Methods >> Object get(Object k), Object put(Object k, Object v), int size(), remove(Object object), boolean isEmpty()

 Iterator à Iterator makes it easier to traverse through the elements of a collection. It also has an extra feature not present in the older Enumeration interface - the ability to remove elements. This makes it easy to perform a search through a collection, and strip out unwanted entries. 

Before accessing a collection through an iterator you must obtain one if the collection classes provide an iterator() method that returns an iterator to the start of the collection. By using iterator object you can access each element in the collection, one element at a time.

 Methods >> boolean hasNext(), object next(),void remove()

 Ex:- ArayList arr = new ArrayList();

       Arr.add(“c”);

       Iterator itr = arr.iterator();

       While(itr.hashNext())

       {

                  Object element = itr.next();

       }

      List Iterator- List Iterator gives the ability to access the collection, either forward/backward direction           

 Legacy Classes

 Dictionary - is an abstract class that represent key/value storage repository and operates much like “Map” once the value is stored you can retrieve it by using key.

   Hash Table - HashTable stores key/value pairs in hash table, HashTable is synchronized when using hash table you have to specify an object that is used as a key, and the value that you want to linked to that key. The key is then hashed, and the resulting hash code is used as the index at which the value is stored with the table. Use H.T to store large amount of data, it will search as fast as vector. H.T store the data in sequential order.

Methods>> boolean containsKey(Object key), boolean containsValue(Object value), Object get(Object key), Object put(Object key, Object value)

 Stack - is a sub class of vector, stack includes all the methods defined by vector and adds several of its own.

 Vector- Vector holds any type of objects, it is not fixed length and vector is synchronized. We can store primitive data types as well as objects. Default length of vector is up to 10.

 Methods>> final void addElement(Object element), final int size(), final int capacity(), final boolean removeElementAt(int index), final void removeAllElements().

 Properties - is a subclass of HashTable, it is used to maintain the list of values in which the “key/value” is String.

     Legacy Interfaces

      Enumeration à Define methods by which you can enumerate the elements in a collection of objects. Enumeration is synchronized.

Methods>> hasMoreElements(),Object nextElement().

 Q) Which is the preferred collection class to use for storing database result sets?

A) LinkedList is the best one, benefits include:

1. Retains the original retrieval order. 2. Has quick insertion at the head/tail 3. Doesn't have an internal size limitation like a Vector where when the size is exceeded a new internal structure is created. 4. Permits user-controlled synchronization unlike the pre-Collections Vector which is always synchronized

ResultSet result = stmt.executeQuery("...");

List list = new LinkedList();

while(result.next()) {

            list.add(result.getString("col"));

}

If there are multiple columns in the result set, you'll have to combine them into their own data structure for each row. Arrays work well for that as you know the size, though a custom class might be best so you can convert the contents to the proper type when extracting from databse, instead of later.

Q) Efficiency of HashTable - If hash table is so fast, why don't we use it for everything?

A) One reason is that in a hash table the relations among keys disappear, so that certain operations (other than search, insertion, and deletion) cannot be easily implemented. For example, it is hard to traverse a hash table according to the order of the key. Another reason is that when no good hash function can be found for a certain application, the time and space cost is even higher than other data structures (array, linked list, or tree).

      Hashtable has two parameters that affect its efficiency: its capacity and its load factor. The load factor should be between 0.0 and 1.0. When the number of entries in the hashtable exceeds the product of the load factor and the current capacity, the capacity is increased by calling the rehash method. Larger load factors use memory more efficiently, at the expense of larger expected time per lookup.

      If many entries are to be put into a Hashtable, creating it with a sufficiently large capacity may allow the entries to be inserted more efficiently than letting it perform automatic rehashing as needed to grow the table.

Q) How does a Hashtable internally maintain the key-value pairs?

A) The Hashtable class uses an internal (private) class named Entry to hold the key-value pairs. All entries of the Hashtable are stored in an array of Entry objects with the hash value of the key serving as the index. If two or more different keys have the same hash value these entries are stored as a linked list under the same index.

Q) Array

            Array of fixed length of same data type; we can store primitive data types as well as class objects.

Arrays are initialized to the default value of their type when they are created, not declared, even if they are local variables 

Q) Diff Iterator & Enumeration & List Iterator

            Iterator is not synchronized and enumeration is synchronized. Both are interface, Iterator is collection interface that extends from ‘List’ interface. Enumeration is a legacy interface, Enumeration having 2 methods ‘Boolean hasMoreElements()’ & ‘Object NextElement()’. Iterator having 3 methods ‘boolean hasNext()’, ‘object next()’, ‘void remove()’. Iterator also has an extra feature not present in the older Enumeration interface - the ability to remove elements there is one method “void remove()”.

 List Iterator

            It is an interface, List Iterator extends Iterator to allow bi-directional traversal of a list and modification of the elements. Methods are ‘hasNext()’, ‘ hasPrevious()’.

Q) Diff HashTable & HashMap

- Both provide key/value to access the data. The H.T is one of the collection original collection classes in java.   H.P is part of new collection framework.

- H.T is synchronized and H.M is not.

- H.M permits null values in it while H.T does not.

- Iterator in the H.P is fail-safe while the enumerator for the H.T is not.

 Q) Converting from a Collection to an array - and back again?

The collection interface define the toArray() method, which returns an array of objects. If you want to convert back to a collection implementation, you could manually traverse each element of the array and add it using the add(Object) method. 

 // Convert from a collection to an array

Object[] array = c.toArray();

 // Convert back to a collection

Collection c2 = new HashSet();

for(int i = 0; i < array.length; i++)

{

   c2.add(array[i]);

}

 Q) How do I look through each element of a HashMap?

A) <select id="swf" name="swf" onChange="showStandardWF()" style="width:175px;">

            <option value="">&lt;Select Standard WorkFlow&gt;</option>

<%

                        hmap =(HashMap)request.getAttribute("stdwf");

                        if( hmap.size() != 0){

                        int len = hmap.size();

                        Set set = hmap.keySet();

                        Iterator it = set.iterator();

                        while(it.hasNext())

                        {

                                    Integer key = (Integer)it.next();

                        %>

                                    <option value="<%=key%>"><%=(String)hmap.get(key)%></option>

                        <%

                        }

                        }

%>      

</select>

 Q) Retrieving data from a collection?

public class IteratorDemo

{

    public static void main(String args[])

    {

        Collection c = new ArrayList();

         // Add every parameter to our array list

        for (int indx = 0; indx < args.length; indx++)

        {

            c.add(args[indx]);

        }

         // Examine only those parameters that start with -

        Iterator i = c.iterator();

         // PRE : Collection has all parameters

        while (i.hasNext())

        {

            String param = (String) i.next();

            // Use the remove method of iterator

            if (! param.startsWith("-") )

                i.remove();

        }

        // POST: Collection only has parameters that start with -

        // Demonstrate by dumping collection contents

        Iterator i2 = c.iterator();

        while (i2.hasNext())

        {

            System.out.println ("Param : " + i2.next());

        }

    }

}

 Q) How do I sort an
array?

A) Arrays class provides a series of sort() methods for sorting arrays. If the array is an array of primitives (or) an array of a class that implements Comparable then you can just call the method directly:

Arrays.sort(theArray);

àIf, however, it is an array of objects that don't implement the Comparable interface then you need to provide a custom Comparator to help you sort the elements in the array.

Arrays.sort(theArray, theComparator);