Programming





What is the need for Collection Framework?

What is the need for Collection Framework?


by Administrator | 22-Mar-2020
Java

Tags:  Core Java  Collection Framework  Array

Share: 


We can declare one integer value by taking one variable like this:

int i =10;

But if we want to declare 100 values, then taking 100 variables to declare 100 values will be very troublesome for the developer. They will have a hard time managing all those variables and the readability of the code will be not very good. To fix this problem we can use Arrays.

By using Arrays we can declare any number of values by using a single variable. Suppose we want to declare 100 integer values. We can achieve that by using the following code:

int[] intArr = new int[100]

In arrays, the values are differentiated by the use of indexes. Here is an example to add a few values to the above declared array of integers:

intArr[0] =9;

intArr[1]=10;

.

.

.

intArr[99]=1;

Note: The numbers inside the square brackets([]) are the index at which the values are stored. The index of arrays start from 0 and end at n-1, n being the size of the array.

By using arrays we’ve improved the readability of code.

But like everything Arrays also have limitations. Here are some of them:

  1. Fixed in size: Once we created an array with any size we cannot increase or decrease the size of that array based on our requirement. The code int[] intArr = new int[100]; from above tells us that we have declared an array of size 100 i.e. we can store a max of 100 integer values into this array. Suppose we only stored 15 values, then the remaining 85 indexes will go to waste.
  2. Can hold only homogeneous elements: Suppose we have an Employee array like this:

Employee[] empArr = new Employee[10];

In Employee Array, we can only declare Employee objects. If we try to add any other type of object like Student or something else, we’ll get compile-time error.

  1. Arrays don’t have any standard data structure: There is no underlying data structure for arrays. This means that we don’t have ready-made method support. If we want to accomplish some out of the box task in arrays then the developer is responsible to write the code. For example to insert elements into the array in some sorting order the developer will have to write the sorting  

In order to overcome these limitations of the Arrays, we need Collection Framework. Here are some advantages of Collections over Arrays:

  1. Grow able in nature: We don’t need to declare the size at the time of declaring a collection. We can add or remove the elements and the Collection will automatically adjust the size.
  2. Can hold both the homogeneous and heterogeneous objects
  3. Every Collection class is implemented based on some standard data structure. We have readymade method support in Collections.

Comments:


There are no comments.

Enter a new Comment:










Copyright Šprgrmmng. All rights reserved.