Tuesday, October 7, 2008

Difference between Collection and Collections

1) Collections - Utility Class with lot of static utility methods like Collections.sort(), Collections.binarySearch().
2) Collection - Is the parent interface of collections framework.

What is the need of abstract class when we have interface in java?

1) In interface we can only have declaration of methods but in abstract class, method implementation can be there.
2) In interface we can only have final static variables.
3) Can implement more than one intefaces, so multiple inheritance is only possible with help of interfaces in java.
4) Interface can have only public method, where as abstract class can have public, protected and private members also.
5) We use abstract class when we want to provide some default implementation to the implementing class and use interface when we want all the methods to be implemented by the subclasses.
One very common question on this point is that why at all do we need interfaces, when same thing can be acheived by abstract classes by declaring all methods as abstract.
Interface force non abstract implementing class to implement all beheviour where as abstract class cannot.


Recommended reading Book By kathy siera for SCJP.

Monday, October 6, 2008

What is java collections framework?

Collection Framework:

Collections basically hold data in a single unit. It might be various kinds of data, and all of the heterogeneous data can be stored as Objects in a single unit called Collection.

Collections Mainly Consist of 3 different parts: -

Interfaces – Allows collections to be manipulated independently of their implementations. Fig (1.1)

Implementations – The concrete classes that are implementations of the interfaces.

Utility Methods – Static methods used for sorting, searching or creating customized collections. E.g. Collections. Sort (Collection)











Core Interfaces of Collections framework

Collection – A basic interface that defines the normal operations that allows a collection of objects to be maintained or handled as a single unit.

Set – Just like mathematics: a set of unique elements. Contains only unique elements and no duplicates. (HashSet, LinkedHashSet)

Sorted Set – Extends set to provide sorted elements in set. (TreeSet)

List – Order of elements is retained. Elements need not be unique. (ArrayList, Vector, LinkedList)

Map – Contains a key and value pair. (HashMap, HashTable, LinkedHashMap)
Sorted Map – Extends Map to store mappings sorted in key order. (TreeMap)


Implementations

Each of collection classes has a constructor for creating a collection based on elements of another collection object passed as argument.
Collection (or map) stores only the references and not the actual objects.
Collection framework is interface based i.e collections are manipulated according to interface types rather than implementations types.
All concrete classes implement Serializable and Cloneable interfaces.