Skip to content

Instantly share code, notes, and snippets.

@viveknaskar
Last active September 12, 2020 06:33
Show Gist options
  • Save viveknaskar/5c8c26f88943b8e01f601db7459cea7d to your computer and use it in GitHub Desktop.
Save viveknaskar/5c8c26f88943b8e01f601db7459cea7d to your computer and use it in GitHub Desktop.
Basics of Collection Framework in a Nutshell

Collection framework

Collection framework is a set of classes and interfaces. It is referred as a collection, but it is used as a library for resusable collection data structures. Both arrays and collections function similarly as they both hold references to the objects and work as a group but the primary difference is that collections do not need to be assigned capacity when they are instantiated as collections can grow and shrink automatically as object are added or removed.

Types of collection

There are basically three types of collection: sets, lists and maps.

Collection

Root interface with basic methods like add(), remove(), contains(), isEmpty(), addAll(), ... etc.

Set

Doesn't allow duplicates. Example implementations of Set interface are HashSet (Hashing based) and TreeSet (balanced BST based). Note that TreeSet implements SortedSet.

List

Can contain duplicates and elements are ordered. Example implementations are LinkedList (linked list based) and ArrayList (dynamic array based)

Queue

Typically order elements in FIFO order except exceptions like PriorityQueue.

Deque

Elements can be inserted and removed at both ends. Allows both LIFO and FIFO.

Map

Contains Key value pairs. Doesn't allow duplicates. Example implementation are HashMap and TreeMap. TreeMap implements SortedMap.

Set vs Map

The difference between Set and Map interface is that in Set we have only keys, whereas in Map, we have key, value pairs.

Advantages of using Collections

  1. Consistent API - The API is a set of interfaces consisting of Collections, Sets, Lists and Maps. All the classes (ArrayLit, LinkedList, TreeMap) that implement these interfaces have common set of methods.
  2. Reduces programming effort considerably. - A programmer does not need to worry about the design the collection and rather think of making the best use of it in the program.
  3. Increases program speed and quality - Collections increases the speed and quality of the code by providing high performance implementation of useful data structures and algorithms.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment