14. Explain the Java Collection framework?


The key interfaces used by the collection framework are List, Set and Map. The List and Set extends the Collection interface. Should not confuse the Collection interface with the Collections class which is a utility class.

A Set is a collection with unique elements and prevents duplication within the collection. HashSet and TreeSet are implementations of a Set interface. A List is a collection with an ordered sequence of elements and may contain duplicates. ArrayList, LinkedList and Vector are implementations of a List interface.

The Collection API also supports maps, but within a hierarchy distinct from the Collection interface. A Map is an object that maps keys to values, where the list of keys is itself a collection object. A map can contain duplicate values, but the keys in a map must be distinct. HashMap, TreeMap and Hashtable are implementations of a Map interface.

How to implement collection ordering? SortedSet and SortedMap interfaces maintain sorted order. The classes, which implement the Comparable interface, impose natural order. For classes that don’t implement comparable interface, or when one needs even more control over ordering based on multiple attributes, a Comparator interface should be used.

Design pattern: What is an Iterator? An Iterator is a use once object to access the objects stored in a collection. Iterator design pattern (aka Cursor) is used, which is a behavioural design pattern that provides a way to access elements of a collection sequentially without exposing its internal representation.


What are the benefits of the Java collection framework?

Collection framework provides flexibility, performance, and robustness.

  • Polymorphic algorithms – sorting, shuffling, reversing, binary search etc.

  • Set algebra - such as finding subsets, intersections, and unions between objects.

  • Performance - collections have much better performance compared to the older Vector and Hashtable classes with the elimination of synchronization overheads.

  • Thread-safety - when synchronization is required, wrapper implementations are provided for temporarily synchronizing existing collection objects.

  • Immutability - when immutability is required wrapper implementations are provided for making a collection immutable.

  • Extensibility - interfaces and abstract classes provide an excellent starting point for adding functionality and features to create specialized object collections.



No comments:

Post a Comment