Collection Tutorial — Collection Framework and Generics

Col­lec­tion is a Java Object that is used to group homo­ge­neous & het­ero­ge­neous, dupli­cate and unique objects with­out size lim­i­ta­tion for car­ry­ing mul­ti­ple objects at a time from one appli­ca­tion to anoth­er appli­ca­tion among mul­ti­ple lay­ers of MVC archi­tec­ture as a method argu­ment and return type.

Why collection class are given when we have object[] to group heterogeneous object ?

All array object has below two prob­lems

  1. It allows us to store only same type of ele­ments.
  2. It is fixed in size.

The first prob­lem can be resolved in using java.lang.Ojbect[]. Using Object[] we can col­lect all types of objects But the sec­ond prob­lem can’t be solved auto­mat­i­cal­ly. We should devel­op below code to solve this prob­lem.

  • Cre­ate array object with ini­tial size and store ele­ments.
  • Once array size is reached its capac­i­ty, exe­cute below steps to store new ele­ment.
    • Cre­ate anoth­er tem­po­rary array with required size.
    • Copy old array val­ues to new array.
    • Add new ele­ment to new array at the end of all its ele­ments
    • Assign new array object ref­er­ence to old array ref­er­enced vari­able.

collection tutorial

All col­lec­tion class­es are defined in java.util pack­age are –

collection tutorial

Why the name collection framework ?

Frame­work is semi-fin­ished reusable appli­ca­tion which pro­vides some com­mon low lev­el ser­vices for solv­ing reoc­cur­ring prob­lems and that can be cus­tomized accord­ing to our require­ment.

Example –

  • Com­put­er is a frame­work, it can be used by all peo­ple accord­ing to their require­ment.

Need of Collection framework classes ?

In Java Col­lec­tion Frame­work class­es are used to store and trans­port objects are of same and dif­fer­ent types with­out size lim­i­ta­tion.

Advantage of collections framework

  • Reduce pro­gram­ming effort by pro­vid­ing use­ful data struc­ture and algo­rithm so you don’t have to write them your­self.
  • Increase per­for­mance by pro­vid­ing high-per­for­mance imple­men­ta­tions of use­ful data struc­ture and algo­ithems.
  • Reduce the effort required to learn APIs by estab­lish­ing a com­mon lan­guage to pass col­lec­tions back and forth.

Types of Col­lec­tion Frame­work Hier­ar­chy

The col­lec­tion frame­work is divide into two hier­ar­chies to store object in array for­mat and (key, val­ue) pair for­mat, they are :

  1. Col­lec­tion Hier­ar­chy
  2. Map Hier­ar­chy

Common Terminology –

collection of objects

The col­lec­tion of object that con­tain oth­er nor­mal class object is called col­lec­tion of objects.

collection of collections

The col­lec­tion of object that con­tain oth­er col­lec­tion object is called col­lec­tion of col­lec­tion.

collection of maps

The col­lec­tion of object that con­tain map object is called col­lec­tion of maps.