Why WE Need Collection
Suppose we want to represent an integer value then we take an integer variable. For example,
If we represent two integer value, then we will take two integer variable.
If we want to represent three integer value, then we will take three integer variable, such as:
Similarly, if we want to represent 10000 integer values then we will take 10000 integer variables. But think and imagine declaring 10000 variables is a worst kind of programming because which value belongs to which variable, it is difficult to identify. That's why readability of the code is not improved.
So to eliminate this disadvantage, we need an array, because we know that more than one similar types of data items can be stored under a single variable, i.e. array. Fig.
An array is an indexed collection of fixed no. of homogeneous data items.
The main advantage of array is we can represent multiple values within a single variable, so that the readability of the code is improved.
Limitations of array:
- Arrays are fixed in size, that means once we create an array with some size, there is no chance of increasing or decreasing the size based on the users requirement.
Arrays contain only homogeneous data items. For example,
student s=new student;
S=new student(); // correct
S=new customer(); // wrong
- Array concept is not implemented based on some standard data structure, hence ready-made method support is not available. For every requirement we have to write the code explicitly which is complexity of programming.
- To overcome these above limitations of array, we should go to Collections.
Introduction To Collection:
- In general Collection is a group of individual objects as a single entity. For exa, collection of books, collection of pens, etc.
- Collection are growable in nature that means based on the user's requirement the size can be either increased or decreased.
- Collection can hold both homogeneous and heterogeneous elements.
- Every Collection class is implemented based on some standard data structure hence ready made method support is available for every requirement. Being a programmer we have to use this method and we are not responsible to provide implementation.
- It is the child interface of Collection.
- If we want to represent group of individual object as a single entity where duplicates are allowed and insertion order must be preserved then we should go to List.
- We can differentiate duplicates using index.
- We can preserve insertion order by using index hence index play very important role in List interface.
- Duplicates are allowed.
- Insertion order is preserved.
Some methods in List interface:
add(int index, Object o);
add(int index, Collection c);
set(int index, Object o); // replacement
© 2018 Silan Technology. All Rights Reserved