Sunday, April 18, 2010

“Quick tour of Collection”
-----------------------------------------------------------
Collection is nothing but way of data storing in specified manner, in Java it’s provided by API’s itself. The performance is based on the correct selection of class which needs to implement in situation.

-----------------------------------------------------------
The core interfaces:

Collection Set SortedSet
List Map SortedMap
Queue


The core concrete implementation classes:

MAPS: HashMap , Hashtable , TreeMap , LinkedHashMap
SETS: HashSet , LinkedHashSet , TreeSet
LISTS: ArrayList , Vector , LinkedList
QUEUES: PriorityQueue
UTILITIES: Array , Collections

Note:
1) Not all collections pass the IS-A test for Collection, that means Not all collections in the Collections Framework actually implement the Collection interface.
2) Specifically, none of the Map-related classes and interfaces extend from Collection. So while SortedMap, Hashtable, HashMap, TreeMap, and LinkedHashMap are all thought of as collections, none are actually extended
from Collection.
3) There are really three overloaded uses of the word "collection”
a): collection (lowercase c), which represents any of the
data structures in which objects are stored and
iterated over.

b): Collection (capital C), which is actually the
java.util.Collection interface from which Set, List,
and Queue extend. (That's right, extend, not
implement.There are no direct implementations of
Collection.)

c): Collections (capital C and ends with s) is the
java.util.Collections class that holds a pile of
static utility methods for use with collections.



DO remember Collections is class with static utility methods, and Collection is interface with common method mostly for all the Collections for example: add (),
remove(), contains(), size(), and iterator().

Collections come in four basic flavors:
Lists Lists of things.
Sets Unique things.
Maps Things with a unique ID.
Queues Things arranged by the order in which they are to be
Processed.


Sub-flavors within these four flavors of collections:

Sorted Unsorted Ordered Unordered

Possible combinations in sub-groups are:
1) Unsorted and unordered: HashSet
2) Ordered but unsorted: LinkedHashSet
3) Both ordered and sorted: TreeSet
4) Sorted but unordered is impossible combination.


Iteration: Iterating through a collection usually means walking through the elements one after another starting from the first element.

Ordered: When a collection is ordered, it means you can iterate through the collection in a specific (not-random) order.

Points:
1) A Hashtable collection is not ordered. Although the Hashtable itself has internal logic to determine the order (based on hashcodes and the implementation of the
collection itself).
2) An ArrayList, however, keeps the order established by the
Element’s index position (just like an array).
3) LinkedHashSet keeps the order established by insertion, so the last element inserted is the last element in the LinkedHashSet (as opposed to an ArrayList, where you can insert an element at a specific index position).







Sorted: A sorted collection means that the order in the collection is determined according to some rule or rules, known as the sort order. A sort order has nothing
to do with when an object was added to the collection, or when was the last time it was accessed, or what "position" it was added at. Sorting is done based on properties
of the objects themselves.

Points: There is two possibilities for sorting if the sorting is taking placed based on natural order, like
1.2.3 or A.B.C that’s ok else if it’s and object and we need sorting on that, we must used Comparator to find the which object needs to take what place.


List Interface: A List cares about the index. The one thing that List has that non-lists don't have is a set of methods related to the index. Those key methods include things like
get(int index), indexOf(Object o), add(int index, Object obj), and so on. All three List implementations are ordered by index position—a position that you determine either by setting an object at a specific index or by adding it without specifying position, in which case the object is added to the end.

ArrayList: just like a growable array. It gives you fast iteration and fast random access. To state the obvious: it is an ordered collection (by index), but not sorted.

Vector: A Vector is basically the same as an ArrayList, but Vector methods are synchronized for thread safety.

LinkedList: A LinkedList is ordered by index position, like ArrayList, except that the elements are doubly-linked to one another. This linkage gives you new methods (beyond what you get from the List interface) for adding and removing from the beginning or end.

Points:
ArrayList is choice in case fast iteration.
LinkedList is choice in case of more deletion and Insertion
Vector is choice in case of thread safe implementation.
Note: Vector is the only class other than ArrayList to
implement RandomAccess.



Set Interface: A Set cares about uniqueness—it doesn't allow duplicates. The equals() method determines whether two objects are identical (in which case only one can be in the set).

HashSet: A HashSet is an unsorted, unordered Set. It uses the hashcode of the object being inserted, so the more efficient your hashCode() implementation the better access performance.

LinkedHashSet: A LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements.

TreeSet: The TreeSet is one of the sorted collections. It uses a Red-Black tree structure, and guarantees that the elements will be in ascending order, according to natural order. Optionally, you can construct a TreeSet with a constructor that lets you give the collection your own rules for what the order should be (rather than relying on the ordering defined by the elements' class) by using a Comparable or Comparator.


Points:
HashSet is good choice in case if no care of iteration
order.
LinkedHashSet is good choice in case iteration needs to take place in same order how they inserted.
TreeSet is good for sorted Set case.

Note: When using HashSet or LinkedHashSet, the objects you add to them must override hashCode(). If they don’t override hashCode(), the default Object. hashCode() method will allow multiple objects that you might consider "meaningfully equal" to be added to your "no duplicates allowed" set.

Map Interface: A Map cares about unique identifiers. You map a unique key (the ID) to a specific value, where both the key and the value are, objects. Even known as key/value or name/value pair. Used equals() method to determine whether two keys are the same or different.

HashMap: The HashMap gives you an unsorted, unordered Map. HashMap allows one null key and multiple null values in a collection.

Hashtable: The Hash is same as HashMap apart from that it’s
Synchronized (that means key methods of class is synchronized). Hashtable doesn't let you have anything that's null nether key nor value.


LinkedHashMap: LinkedHashMap collection maintains insertion order (or, optionally, access order).

TreeMap: A TreeMap is a sorted Map. And that by default, this means "sorted by the natural order of the elements.
Sorting can be defined by user of collection as well.

Points:
HashMap is good choice in case no order required during iteration and may have null.
Hashtable is good choice for thread safe and if we don’t allow any null.
LinkedHashMap is good choice for fast iteration.
TreeMap is good choice for sorted Map.


Queue Interface: A Queue is designed to hold a list of things to be processed in some way. Although other orders are possible, queues are typically thought of as FIFO (first-in, first-out). Queues support all of the standard Collection methods and they also add methods to add and subtract elements and review queue elements.

PriorityQueue: The Since the LinkedList class has
been enhanced to implement the Queue interface, basic queues can be handled with a LinkedList. The purpose of a PriorityQueue is to create a "priority-in, priority out"
queue as opposed to a typical FIFO queue. A PriorityQueue's elements are ordered either by natural ordering (in which case the elements that are sorted first will be accessed first) or according to a Comparator. In either case, the elements' ordering represents their relative priority.


Summary:
HashMap: Fastest updates (key/value pairs); allows one null key, many null values.

Hashtable: Like a slower HashMap (as with Vector, due to its synchronized methods). No null values or null keys allowed.
LinkedHashMap: Faster iterations; iterates by insertion order or last accessed; allows one null key, many null values.

TreeMap: A sorted map.

PriorityQueue: A to-do list ordered by the elements' priority.

Need to do for Using the Collection:
1) Overriding the equals() method:
What does equals() method do, is to compares if both the
Objects meaningfully same rather than reference (==).

If you don't override a class's equals() method, you won't be able to use those objects as a key in a Hashtable and you probably won't get accurate Sets, such that there are no conceptual duplicates.
Default behavior of equals() method is same as ==.

2) Overriding the toString() method:
This is optional, have no fatal impact, however can make
Information more generic to understand by non
Professionals even.

3) Overriding the HashCode() method:
The HashCode is directly impacts the performance. A good
Hashcode logic may improve the potential performance.
HashMap and HashSet use the hashcode value of an object
to determine how the object should be stored in the
collection, and the hashcode is used again to help
locate the object in the collection.


Collection is uncompleted without generics.





Reference Book: SCJP(KS) and Thinking in Java

Thanks: Dated:
Document Editor: 19th April 2010
Dewendra K Pandey
dewendra1@gmail.com

The very essence of education is concentration of mind, not the collecting of facts. Concentration of the mind is the source of all knowledge. Swamy Vivekananda.

-------------------------------------------------------

2 comments:

  1. Boss Tell me How to make an Synchronized array list????

    ReplyDelete
  2. Thanks yor very much for your question Sir,

    I got exposure to look Java.doc for Collection to understand these methods, when i was looking for your answer.
    static void synchronizedList(List)
    static void synchronizedMap(Map)
    static void synchronizedSet(Set)
    static void synchronizedCollection(Collection)
    even for sorted Map/Set are there in Collections, these methods makes them synchronized.

    Even though it's not good approch whne you have synchronized version of each collection present.
    ArrayList arrayList = new ArrayList();
    List list = Collections.synchronizedList(arrayList);

    ReplyDelete