Sunday, 27 October 2013

Collection Framework Part-1

Introduction:

This blog is about java collection framework. We designed this post by keeping beginner and intermediate learner in mind.

Joshua Bloch
Joshua Bloch
For collection framework  you no need to add any external jar file. it's an inbuilt feature in java since JDK 1.2 release.You can find  source code of collection in rt.jar(inbuilt jar). Collection framework is also know as Java Data Structure as we can find almost all data structure implementation in this library.

The chief design and implementer of collection framework is Joshua Bloch and currently he is associated with Google a former employee of
Sun Microsystem.

As Collection  Framework is a big part so we thought of dividing it into 3 part and this is the first part.

What is Collection Framework?

In simple Collection Framework is a library to handle group of object

As you know java is Object Oriented. So it's a common requirement to play with object like make them in a single group based on type, Storing  them not only that after storing we need to retrieving them when ever we need and performing some basic task like searching and sorting etc. These are few most common requirement we need.

So in case of c and c++ you have to define and write your own  algorithm and logic in order to full fill the above requirement. But fortunately java is API based and everything is readily available . The only thing we need to know is, how to use it. In other word we have to know how to store and get object from Collection.

All common used collection members you'll find in java.util package.

Why Collection Framework?

 As we told this is a library to handle group of object, so definitely you may rise a question like why not object array why all the useless stuff. Of course you are right you can handle a group of object using object array but the problem with  array is
  • Array is not allowing to store dissimilar type of object in other word we can not store different class object into the same array which is frequent requirement in Java(of course you can do it using an object array but its some what lander).
  • Adding object at the end of array is easy but inserting and deleting the element in middle of the array is difficulty. In this case we have to re-arrange all the element.
  • Retrieving the element from an array is easy but after riveting the element , if we want to process them, then there are no method available to carry out this.
Due to these problem programmer want a better mechanism to store a group of object. The alternative is using an object to store a group of object. It means that we can use a class object as an array . Such an object is called as Collection Object.

Advantage of using  Collection Framework.

Collections framework is worth your effort and will benefit your programming in many ways. Below i listed few benifity
  • As it's API based(a predefined library) so no need to write your own logic to store and retrieve element, the only thing you want to do is call a predefined method to store or retrieve object.
  • It dramatically increases the readability of your collections by providing a standard set of interfaces to be used by many programmers in many applications.
  • It makes your code more flexible by allowing you to pass and return interfaces instead of concrete classes, generalizing your code rather than locking it down.
  • You can customize  searching and sorting as per your requirement.

 

Overview about java.util package.

 As we already told collection framework is a library and in this library you can find a lot of common used class and interface which is inside java.util package. 

Overview about java.util package
Overview about java.util package.


The main interface of the collection framework is java.util.Collection. Here I am assuming that you are strong in java interface. java.util.Collection internally extends another interface known as java.lang.Iterable. 

By implementing/extend Iterable interface an object can take the advantage of "foreach" statement, we'll discuss about it in next heading.

So all classes and intefaces comming under java.util , we can brodly catagories inot two part
  • Collection by value(java.util.List, java.util.Set and implementation Classes)
  • Collection by key and value pair (java.util.Map and implementation Classes)

 Collection by value:

Using this type of collection we can  store only value and basically it's index based like Array.

Under this java.util.List, java.util.Set and Java.util.Queue. All 3 are interface are directly extending Java.util.Collection. All other classes and interfaces of java.util capable to store value will come under these parent interfaces.

Collection by key and value pair:

Using this type of collection we can store value corresponding to a key where key will be unique and not null.

Under this java.util.Map(an interface) will come which isn't a chile of java.util.Collection Interface and it is a parent interface for key value pair of collections.In other word  all other classes/interfaces capable to store key and value will come under Map interface.

Package Hierarchy for Java Collection Framework
Package Hierarchy for Java Collection Framework

 

How to store and retrieve from Collection.

 To store element in a collection several predefined method are there and it depends upon which collection you are using. In case of set and list add() method  whereas in case of map put() method.

Similarly to retrieve element we have get(int index) method for value pair and get(Object key) for key value pair.But using this mechanism you can retrieve a specific element you can't retrieve all the element.To retrieving all element  you have to user following ways.

In general there are 4 different way to retrieving elements form collections
  • For-each loop.
  • Iterator interface.
  • ListIterator interface.
  • Enumeration interface.
  • For loop(not a wise solutions)

For-each loop :

For-each loop is live for loop which repeatedly executes a group of statement for each element of the collection.Unlike for loop you no need to give any interment or end limit.
Syntax:

for(Variable : Collection-object)
{
      Statement
}

Iterator interface:

Iterator is an interface that contains method to retrieve elements one bu one from a collection object.It has 3 method.
  • boolean hasNext() - This method returns true if the iterator has more elements.
  • element next()- This method returns the next element in the iterator.
  • void remove()- This method will remove the last element return by the iterator from the collection. 

ListIterator interface:

ListIterator is an interface that contains method to retrieve elements from a collection object both in forward and reverse direction.It has many method but below we listed few important methods
  • boolean hasNext() - This method returns true if the ListIterator has more elements while traversing in forward direction.
  • boolean hasPrevious() - This method returns true if the ListIterator has more elements while traversing in reverse direction.
  • element next()- This method returns the next element in the iterator.
  • element previous()- This method returns the previous element in the iterator.
  • void remove()- This method will remove the last element return by the next or  previous method .

Enumeration interface:

The functionality of this Enumeration interface is duplicated by the Iterator interface. In addition, Iterator adds an optional remove operation, and has shorter method names. New implementations should consider using Iterator in preference to Enumeration.

It has two method
  • boolean hadMoreElements()- This method returns true if the iterator has more elements.
  • element nextElement()- This method returns the next element in the Enumeration.

 For loop:

For loop is as usual.

 

How to work with java.util.List. 

List is an interface which will allow you to store collection of value.The followings are list of classes which implements List.

Interface List<E>

E - the type of elements maintained by this List

All Known Superinterfaces:

Collection<E>, Iterable<E> 

All Known Implementing Classes:

AbstractList, AbstractSequentialList, ArrayList, AttributeList, CopyOnWriteArrayList, LinkedList, RoleList, RoleUnresolvedList, Stack, Vector.

Properties of List:

  • An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.
  • Unlike sets, lists typically allow duplicate elements. More formally, lists typically allow pairs of elements e1 and e2 such that e1.equals(e2), and they typically allow multiple null elements if they allow null elements at all.

An overview about different  methods of List:

The List interface provides following method to insert element/Object
  1. add(E e): Appends the specified element to the end of this list (optional operation).
  2. add(int index, E element): Inserts the specified element at the specified position in this list (optional operation).
  3. addAll(Collection<? extends E> c): Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator (optional operation).
  4. addAll(int index, Collection<? extends E> c): Inserts all of the elements in the specified collection into this list at the specified position (optional operation).
The List interface provides following methods to access  list elements
  1. get(int index): Returns the element at the specified position in this list.
  2. iterator(): Returns an iterator over the elements in this list in proper sequence.
  3. listIterator(): Returns a list iterator over the elements in this list (in proper sequence).
The List interface provides two methods to search for a specified object.
  1.  indexOf(Object o):Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.
  2. lastIndexOf(Object o): Returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element.
 The List interface provides following method to remove element/Object
  1. remove(int index): Removes the element at the specified position in this list (optional operation).
  2. remove(Object o):Removes the first occurrence of the specified element from this list, if it is present (optional operation).
  3. removeAll(Collection<?> c):Removes from this list all of its elements that are contained in the specified collection (optional operation).
  4. retainAll(Collection<?> c)Retains only the elements in this list that are contained in the specified collection (optional operation).
Other Methods.
  1. isEmpty(): Returns true if this list contains no elements.
  2. contains(Object o): Returns true if this list contains the specified element.
  3. clear(): Removes all of the elements from this list (optional operation).
  4. size(): Returns the number of elements in this list.

Examples:

Source code: http://ideone.com/cgNBex
List Demo
How to use List
 Source code: http://ideone.com/p0uGMk
Common operation on List
Common Operation With List

 

How to work with java.util.Set.

Set is an interface which is allowing to store collection of unique value. The followings are list of classes which implements Set

General deceleration: Interface Set<E>
E - the type of elements maintained by this set 

All Known Subinterfaces: NavigableSet<E>, SortedSet<E>

All Known Superinterfaces: Collection<E>, Iterable<E>

All Known Implementing Classes: AbstractSet, ConcurrentSkipListSet, CopyOnWriteArraySet, EnumSet, HashSet, JobStateReasons, LinkedHashSet, TreeSet

Properties of Set:

  • A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction.
  • Some set implementations have restrictions on the elements that they may contain. For example, some implementations prohibit null elements, and some have restrictions on the types of their elements. 

An overview about different  methods of Set:

The Set interface provides following method to insert element/Object
  1. add(E e): Adds the specified element to this set if it is not already present (optional operation).
  2. addAll(Collection<? extends E> c): Adds all of the elements in the specified collection to this set if they're not already present (optional operation).
  3.  
The Set interface provides following methods to access  list elements
  1. iterator(): Returns an iterator over the elements in this set. 
The Set interface provides following method to remove element/Object
  1. remove(Object o): Removes the specified element from this set if it is present (optional operation).
  2. removeAll(Collection<?> c): Removes from this set all of its elements that are contained in the specified collection (optional operation).
Other Methods.
  1.  retainAll(Collection<?> c):Retains only the elements in this set that are contained in the specified collection (optional operation).
  2. size(): Returns the number of elements in this set (its cardinality).
  3. clear(): Removes all of the elements from this set (optional operation).
  4. contains(Object o): Returns true if this set contains the specified element.
  5. isEmpty(): Returns true if this set contains no elements.

Examples:

How to use Set
How to use Set
Common operation on Set
Common operation on Set

 

How to work with java.util.Map. 

Map is an interface which will allow us to store in key and value pair.The followings are list of classes which implements Map.
General deceleration: public interface Map<K,V>
K - the type of keys maintained by this map.
V - the type of mapped values .

All Known Subinterfaces: Bindings, ConcurrentMap<K,V>, ConcurrentNavigableMap<K,V>, LogicalMessageContext, MessageContext, NavigableMap<K,V>, SOAPMessageContext, SortedMap<K,V>

All Known Implementing Classes: AbstractMap, Attributes, AuthProvider, ConcurrentHashMap, ConcurrentSkipListMap, EnumMap, HashMap, Hashtable, IdentityHashMap, LinkedHashMap, PrinterStateReasons, Properties, Provider, RenderingHints, SimpleBindings, TabularDataSupport, TreeMap, UIDefaults, WeakHashMap 

Properties of Map:

  • Map is an collection object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.
  • This interface takes the place of the Dictionary class, which was a totally abstract class rather than an interface.
  • The Map interface provides three collection views, which allow a map's contents to be viewed as a set of keys, collection of values, or set of key-value mappings.
  • The order of a map is defined as the order in which the iterators on the map's collection views return their elements. Some map implementations, like the TreeMap class, make specific guarantees as to their order; others, like the HashMap class, do not.
  • Some map implementations have restrictions on the keys and values they may contain. For example, some implementations prohibit null keys and values, and some have restrictions on the types of their keys.

An overview about different  methods of Map:

 The Map interface provides following method to insert element/Object
  1. put(K key, V value): Associates the specified value with the specified key in this map (optional operation).
  2. putAll(Map<? extends K,? extends V> m): Copies all of the mappings from the specified map to this map (optional operation).
The Set interface provides following methods to access  list elements
  1. entrySet(): Returns a Set view of the mappings contained in this map.
  2. keySet(): Returns a Set view of the keys contained in this map.
  3. values(): Returns a Collection view of the values contained in this map.
 The Set interface provides following method to remove element/Object
  1. remove(Object key)Removes the mapping for a key from this map if it is present (optional operation).
 Other Methods:
  1. containsKey(Object key): Returns true if this map contains a mapping for the specified key.
  2. containsValue(Object value): Returns true if this map maps one or more keys to the specified value.
  3. isEmpty(): Returns true if this map contains no key-value mappings.
  4. int    size(): Returns the number of key-value mappings in this map.

Examples:

Different way of iterating a Map
Different way of iterating a Map
Common Operation With Map
Common Operation With Map

 

Which collection is the best for your Requirement. 

 

What to use when
What to use when

Assignment for you!!!(Comment Your Answers)

  1. Why do we need iterator, ListIterator,  Enumeration even though for loop is there. We can user add() remove() etc to do all common operation with collections?
  2. How does the following two line differs:                                                                                  >>ArrayList<String> bird = new ArrayList<String>();
            >>List<String>  bird  = new ArrayList<String>();
  3. What is the new feature added in JDK 1.7 w.r.t collection deceleration and initialization.
  4. How to  get a specific element form a Set e.g in case of  List we are using get(...)?
  5. Why Set doesn't have any method to get the element by index?
  6. Is it possible to use listIterator w.r.t Set. yes or no answer with reason?
  7. How ArralyList is differs from Vector?
  8. How HashMap is differs from HashTable.

 

Reference:

 

4 comments:

  1. thank you very much for this insight. Thanks for your book "Effective Java"

    ReplyDelete
  2. Play at Lucky Club Casino Site
    Lucky Club Casino is a fully licensed casino with licenses from Malta, UK, and Gibraltar. They are powered by Evolution Gaming. This online gambling platform has  Rating: 4 · ‎32 votes luckyclub

    ReplyDelete
  3. Play Free Slots at Casinos Near Me | Mapyro
    Discover 의왕 출장마사지 the 당진 출장안마 best online slot 화성 출장샵 games with free spins and instant play. Find the best 경상북도 출장안마 casinos 인천광역 출장안마 with free spins and real money.

    ReplyDelete