Why need of Collection in java? In simple words, the Java Collections Framework allows you to use the right data structure because one size does not fit all. Java Collections is come up with different functionality, convenience, and usability.
We have two approaches:
- Individual variable approach:
Individual variable approach:
- Suppose we want to create or store one int value in the memory. Like int x=10, here x is representing INT type value. Now suppose I want to store one more value I will create another variable int y=10; So on and so forth I can create a variable but If suppose I need to allocate 1000 variable or values. We can create 1000 variable but its not a good programming practice or it will not be readable.
- So, Declaring 1000 variables is a worst kind of programming practice.
- Readability and reusability of the code will be down because which variable represents to which value is difficult to tell and remember.
TO OVERCOME ALL THSESE PROBLEMS WE SHOULD GO FOR ARRAYS CONCEPT.
An array is an indexed collection of fixed number of homogeneous data elements.
- In array we can represent multiple values with a single variable.
- Reusability of the code will be improved.
Limitations of object type arrays:
- Arrays are fixed in size: Once we created an array with some size there is no chance to increase and decrease its size based on our requirement, Hence to use arrays compulsory we should know the size in advance which may or may not possible.
- Arrays can hold only homogeneous data elements.
Student s = new Student; (Correct)
S = new Customer; (Wrong)
Compiler Exception: Incompatible type
But we can resolve this problem by using object arrays.
Object o = new Object;
o = new Student;
o = new Customer;
Arrays 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.
Individual Variable Approach
Huge number of variable
Student  S = new Student;
0 0 0
0 1 2 3 ————————- 999
We can represent huge no. of variable by using a single variable S
- Array concept is not implemented using any datastructure.
Suppose we want to insert element in some sorting order than who will responsible to write the sorting code programmer
But in collection readymade method support is available for sorting we can use Tree Set (Automatically element will insert in some sorting order)
- Second, If we want to search whether the particular element is present or not. So in arrays we will have to write the searching codes.
But in collection we have one readymade method called contains()
1. Fixed in size.
2. Homogenous elements
3. Underlying DS
TO OVERCOME ALL THESE PROBLEMS WE SHOULD GO FOR COLLECTIONS CONCEPT