The need for Collection:
Array: An Array is an indexed collection of a fixed number of homogeneous data elements.
Using arrays the main advantage is we can represent multiple values in a single variable by using arrays. So that Readability of the Code will be Improved.
There are some limitations of object type arrays:
- Arrays are fixed in size that means if Once we created an array there is no chance of increasing or decreasing size based on our requirement. So when we are using arrays it is compulsory we should know the size of arrays in advances which may not be possible every time.
- Arrays can hold only homogeneous data type elements. Example:
Student s = new Student;
s = new Student(); // Working beacuse we are creating Student object. Student s = new Student;
s = new Customer()); //We are getting error CE: incompatible types found: Customer required: Student
- Arrays Concept is Not implemented based on some standard data structure, hence readymade methods support is not available. Hence for every requirement, we have to write the code explicitly which increases the complexity of the programming.
To Overcome this type of arrays problems we should go for Collection.
What are the main advantages of collection:
- The collection is growable in nature. That means we can change the size(Increase OR Decrease) based on Our Requirement.
- It can hold both homogeneous and Heterogeneous Elements.
- Every collection Class is implemented based on some standard data structure. Hence for every requirement readymade method support is available. Being a programmer we have to use those methods and we are not responsible to provide the implementation.
When we want to Represent a Group of Individual Objects as a Single Entity then we should go for Collection.
Differences Between Arrays And Collection:
- Arrays are fixed in size.
- With respect to memory, arrays are not recommended to use.
- With respect to performance, arrays are recommended to use.
- Arrays can hold only homogeneous data elements.
- Arrays can hold both Primitives and Objects.
- Arrays concept is not implemented based on some standard data structure. Hence readymade method support is not available.
- The collection is growable in nature.
- With respect to memory, collections are recommended to use.
- With respect to performance, collections are not recommended to use.
- Collection can hold both Homogeneous and Heterogeneous elements.
- Collection can hold only objects but not primitives.
- For every collection class, the underlying data structure is available hence readymade method support is available for every requirement.
Collection Frame Work:
It defines several Classes and Interfaces which can be used to represent a group of Objects as
a single entity.
There are mainly 9 Key Interfaces Of the Collection Framework.
- Collection (I)
- List (I)
- Set (I)
Hope this was helpful for you. If you have any questions please feel free to leave a comment. Thank you for reading.