Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




Java - Collections

Collections, as the name suggests is going to collect something. And since, java only deals with objects. The java Collections is going to hold objects.


Why do we need java Collections to store objects?

Example :

Just think for a moment! If you were given the responsibility to manage the Student records in a school. What would you do?


class Student {

  String name;
  int age;
  String roll;
  String standard;
}

You would create the above student class and start creating objects for every students. But there could be thousands of students in a school.



The Problem

How would you sort the student objects if you are asked to sort the students by age?How would you find out who is the eldest student in the school?And so on..

To maintain this huge number, java Collections comes into picture.

Collection is a framework in java which has some inbuild classes and interfaces in it, that helps in effective searching, sorting, deletion, insertion etc of an object.


How Collections framework is implemented?

To make use of Java Collections, you have to put all your objects into the 'Collection'. And Collections framework will do the rest for you.



Collections framework Hierarchy

So, there is an interface called 'Collection' but it doesn't do the sorting, searching etc on the objects all by itself. It has a few more interfaces and classes which helps it perform the task. Let's look at the below hierarchy:

java_Collections

As we can see in the above diagram there are two interfaces List and Set which are the direct child of Collection Interface.


What is the purpose of List and Set?

'List' can contain duplicates whereas 'Set' will never accept duplicates.

Also 'List' is indexed.

Example of indexed List:
Whenever you are inserting elements into the List it will be inserted in the same order. It is same as a group of students entering an assembly hall, in a line based on their roll numbers. Even when they comes out they will come based on their roll numbers.

Whereas Set is not indexed.

Example of non-indexed Set:
The insertion order will not be maintained. It's same as a group of people entering a stadium in a line. Once they are inside the stadium they will they will grab a seat where ever they can.

Next, we will dig more on Lists. As we see two concrete implementations of Lists. i.e. ArrayList and LinkedList which we will be looking next.