Java Collections Framework

 Collection: 

  • Group of objects
  • Single entity representing multiple objects

Collection Framework:
To represent a group of objects into a single entity we need certain number of classes and interfaces. And Collection Framework provides those classes and interfaces.

Arrays


Limitations of Arrays:
1. Arrays lets us store only homogenous or same kind of data or data of same type

Workaround:
Create Object Array or Array of object type:
This can allow us to store homogenous as well as heterogeneous data


2. Array has limited size. 
3. Has fixed size. Cannot increase or decrease the size at runtime. Means it is not growable in nature.
Means before we create an array we must know how many elements we are going to store in the array.
 Not possible to add new or remove existing values during runtime. To do that we will need a programming logic. Cannot add more elements at runtime to the array and memory gets wasted if we do not use all the memory initially allocated.
4. Has no underlying data Structure. So it cannot support and readymade or inbuilt method. I have to         write a programming logic for that.


To overcome the above limitations of Arrays, we use Collection framework in Java





Collections:
  • ArrayList
  • HashMap
  • Vector
  • Tree
  • LinkedList
  • ...
Basic Differences between Array and Collections:


Classes and interfaces available in Collection Framework
Main interfaces and the derived classes available:

Collection(I) : is a root interface for all other collection related classes and Interfaces
It is also a group of objects represented by single/ common entity.
Used to represent group of elements as a single entity.



Collections is a class from java.util package:







NB: I stands for interfaces. These are all interfaces
List, Set and Queue are child interfaces of root Collection Interface and extended from Collection Interface

List Interface:
  • Used to represent group of elements when insertion order is preserved
  • And duplicate elements allowed


List interface is implemented using the following classes:
  • ArrayList
  • LinkedList
  • Vector is kind of a collection extended from Stack. Vector and Stack are legacy classes


Set Interface:
  • Used to represent group of elements when insertion order not is preserved
  • And duplicate elements is not allowed

List interface is implemented using the following classes:
    • HashSet
    • LinkedHashSet
    Differences between ...:

    Queue Interface:
    • Used when we have objects which are to be queued in an order prior to processing
    • Uses FIFO

    Queue interface is implemented using the following classes:
      • PriorityQueue


      Map Interface:
      • Independent Interface of Collection
      • Not related to Collection Interface
      • Not child I of Collection(I)

      When we need to go for Map Interface:
      • When the objects are or we want to store the objects in the form of Key & Value pair
      • Keys are unique and cannot be duplicate
      • Values can be duplicate
      Map interface is implemented using the following classes:
          • HashMap
          • LinkedHashMap

          -----------------------------------------------------------------------------------------------------------------------------Java Collections Framework-Part3 | Interfaces And Classes | Methods in Collection & List Interfaces




          • Methods available in Collection I are also available in List, Set and Queue I
          • And additionally List, Set and Queue I has their own methods
          • Collection I is a root I that has methods common to all its child Collection Interfaces

          Methods available in Collection I. These are also commonly available in List, Set and Queue I. And the below methods are abstract methods, with definition but no implementation and are implemented by ArrayList and LinkedlList:
          • add(object o)      // Add a single object to the collection
          • addAll(C)      // Add multiple object to the collection object C
          • remove(object o)   // Removes one object o from the collection
          • removeAll(C)     // Removes all the objects from the collection C
          • retainAll (C)              // Removes all the objects from the collection except the object C
          • clear()                 // Clears all objects from the Collection
          • isEmpty()           // Checks if the collection is empty of not
          • size()                  // How many objects are in the collection
          • contains(object o)   // Checks if the collection contains the object o
          • containsAll(Collection C)   // Checks if all the group of elements are present in the collection
          • toArray(Collection C)       // Convert collection into array format. An object array will be returned


          Methods available in List I in addition to the above collection methods. And notably they have index as a parameter:
          • add(index, Object o)
          • addAll(index, Collection C) 
          • remove(index)
          • get(index)    // Returns the object at the given index)
          • set(index, object o)   // Replaces the existing object at the given index with a new object)
          Comparison of methods available in Collection I and List I:


          -----------------------------------------------------------------------------------------------------------------------------
          Java Collections Framework-Part4 | ArrayList Concept | Hands-on

          ArrayList Class:

          Behavior:
          • ArrayList is a growable object
          • Insertion ordered is preserved
          • Duplicates allowed
          • Accepts heterogenous data elements
          • Can be restricted to accept specific type of data elements or specific or similar type of objects
          • In case of ArrayList, all the objects/ elements are stored in consecutive order





          Declaration:
          • Default number of locations allocated in ArrayList is 10




          • If we do not specify any no. of locations in the ArrayList, by default 10 will be allocated and leter if we keep on adding new elements, automatically the size will be growable
          • Accepts heterogenous data elements <The 1st declaration in the above fig>
          • Can be restricted to accept specific type of data elements or specific or similar type of objects <The 2nd declaration in the above fig>


          Methods available inside ArrayList class:
          • add(obj)                                    // Adds the object at the end of the Array
          • add(index, Obj or value)          // Adds the object at the specified index in the Array
          • size()                                        // find how many objects or elements are there in the ArrayList
          • remove(index)                         // Remove objects or elements from the ArrayList
          • get(index)                                // Retrieves an object or element or value from the ArrayList
          • set(index, new Object or element)   // Replace or change the object or element at a given index with an  new object or element in the ArrayList
          • al,contains(obj)                       // Searches for an object or element if it is present in the ArrayList. Returns True/ False
          • isEmpty()                 // Verifies if the ArrayList is empty of has some values. Returns True/ False
          • addAll()                   // Adds group of objects or elements to the ArrayList
          • removeAll()                   // Removes group of objects or elements from the ArrayList
          • collections.sort(al)    // Use Collections class utility methods to sort the objects or elements in the ArrayList. The elements must be homogeneous for it to be sorted. al is the ArrayList ref variable
          • Collections.shuffle(al)                                         // Shuffles all the elements in the ArrayList
          • ???                                                                       // convert an array to ArrayList





          -----------------------------------------------------------------------------------------------------------------------------
          Java Collections Framework-Part5 | Linked List Concept | Hands-on

          LinkedList:
          • is a class that is implemented from List Interface and which in turn is implemented from Collection root interface
          • In addition to methods in List I, it also implements some methods from the Queue Interface (specifically from Deque Interface)
          • Can also insert Null
          • Objects/ elements are/ may not be stored in consecutive order, arranged randomly, and linked by the addresses of those elements
          • Implemented upon Doubly Linked list data structure


          Behavior:
          • There is no default size in LinkedList as it will internally maintain all elements in the form of nodes
          • In LinkedList, Insertion ordered is preserved like ArrayList
          • Duplicates elements are allowed like ArrayList
          • Additional attributes in LinkedList follows below:


          When we choose one over the other:
          • Do not choose ArrayList when we need to do more no. of insertion and deletion operations. This is because performance will be affected due to shifting of many/ more no. elements due to insertion or deletion
          • It is recommended to choose ArrayList for retrieval operations and more specifically when there are more no. of retrieval operations and not prefer LinkedList 
          • For more no. of insertion and deletion operations, it is not recommended to go for ArrayList 

          • We prefer LinkedList when there are more no. of insertion and deletion operations
          • In case of ArrayList, all the objects/ elements are stored in consecutive order
          • In case of LinkedList , all the objects/ elements are stored randomly wherever memory is available and all the elements will be linked together with the address


          How LinkedList is organized:
          • Each part is called node with an index.
          • Every node has 3 parts:
          • First part has previous element address
          • The 2nd part has the element
          • The 3rd part represents the address of the next element


           Insertion:



          Deletion:





          Upon deletion, element at index 2 is sent for garbage collection.

          LinkedList is recommended for insertion and deletion operation.

          LinkedList not preferred in the collections:
          When there are more no. of retrieval operations as it will take lot of time


          Preference when there are more no. of Insertion/ deletion and Retrieval:



          methods available in LinkedList class:
          • methods available in List(I) are also available in ArrayLista nd LinkedList
          • LinkedList also implements methods available in Deque(I)
          • Below are the methods implemented from List Interface

          LinkedList preferred to develop stacks(FILO) and queues(FIFO):




          methods specific to or additional methods available in LinkedList class:



          • These are specifically used to implement stacks and queues


            •     addFirst(obj)



            •     addLast(Obj)


            •    removeFirst()




            •     removeLast()
          • Demo --Starting at 30 mins
          -----------------------------------------------------------------------------------------------------------------
          Java Collections Framework-Part6 | HashSet Concept | Hands-on



          HashSet class:
          We go for it when:
          • Duplicates not allowed
          • It's an unordered list. Insertion order not preserved. That's why there is no index concept in HashSet 
          • Inserts the elements using HashCode
          • Searching of elements will be fast in HashSet
          • We choose it when there are more no. of search operations.
          • Heterogeneous data and Null will be supported

          Create HashSet Objects:
          • How it stores and locates elements:
                      HashSet  hs = new HashSet();  

                      HashSet() is the default empty constructor and will create16 initial locations and allow us to                     store 16 objects/ elements

                      Load Factor/ fill Ratio of HashSet = 0.75

          Config initial value and Load Factor of HashSet:

                      HashSet  hs = new HashSet(100);  //  Load Factor = 0.75 by default as it is not specified. Here it will allocate heterogeneous data
                      HashSet  hs = new HashSet(100,0.95);  //  Here we have specified the Load Factor to 0.95. Here it will allocate heterogeneous data
                      HashSet  <Integer> hs = new HashSet <Integer> ();  //   Here it will allocate homogeneous data/ object of type Integer as we are specifying it

          Methods available in HashSet class:
          • HashSet does not have any method specific to it. It implements all the methods available in Set Interface


          • Sorting and shuffling not possible as there is not index concept here


          • Methods are availbe in HashSet to find Union, Intersection and difference of two sets, but unionAll is not avaialble since duplicates are not allowed in HashSet
          • Demo --Starting at 18 mins
          -----------------------------------------------------------------------------------------------------------------

          Java Collections Framework-Part7 | LinkedHashSet Concept | Hands-on

          LinkedHashSet class:


          Basic difference between HashSet and LinkedHashSet:
          • All the HashSet methods are also applicable for LinkedHashSet class


          • Demo --Starting at 4:35 mins
          -----------------------------------------------------------------------------------------------------------------
          Java Collections Framework-Part8 | Queue Concept | Hands-on


          When we have to go for Queue and what elements we can store in queue:
          • Used for Group of elements which are prior to processing
          • Examples:


          How elements are stored in queue:    Using FIFO


          Methods implemented in LinkedList and PriorityQueue class from Queue(I):











          • heterogeneous data not allowed in PriorityQueue
          • heterogeneous data allowed in LinkedList 

          • Demo --Starting after 18:00 mins
          -----------------------------------------------------------------------------------------------------------------
          Java Collections Framework-Part9 | Map & HashMap Concept | Hands-on


          • Map is not a child I of Collection(I).
          • It is independent of Collection(I).
          • Map I is implemented by HashMap and HashTable Classes

          When we need to go for Map(I):
          • When we want to represent a group of objects where key-value pair exists
          • Combination of key-value is called data set or pair or entry
          • key and value is tightly coupled
          • Every Key is an object and also every Value is an object 
          • Duplicate keys are not allowed
          • Values can be duplicated




          Map I is implemented using multiple classes:
          • Map is an I implemented by HashMap Classes
          • HashMap is a collection of key and value pairs


          • Whatever attributes or methods that are applicable for Map I, same are applicable for HashMap class
          • HashMap is implemented using the underlying data structure HashTable
          • Insertion order not preserved in HashMap. This is applicable to collection that is implemented using HashMap data structure
          • Null key allowed only once as keys are unique
          • Multiple Null values allowed
          Different methods available in the HashMap class:







          • Return type of keyset() is set since duplicates are not allowed in Keys and also in sets
          • Return type of keyset() is collection as values can be duplicate
          • Return type of entryset() is set since duplicates are not allowed in key-value combination as in sets
          Entry Interface: It is a sub-interface of HashMap. It is not a child interface but a subset of HashMap class





          Methods available in Entry Interface: 
          • Entry means combination of one key and one value
          • Entry set means all the key value pairs

          • Demo --Starting after 30:00 mins
          -----------------------------------------------------------------------------------------------------------------
          Java Collections Framework-Part10 |Hashtable Concept | HashMap Vs Hashtable | Hands-on
          • Hashtable is a collection and is a class that implements Map Interafce

          HashMap & Hashtable Similarities:
          • Insertion order not preserved as it uses the underlying data structure of HashTable/HashCode


          HashMap & Hashtable differences:
          • In HashMap, duplicate key as null is not allowed but it is allowed in Value
          • In Hashtable, null is not allowed as key or value

          Methods implemented in Hashtable class:

          Demo --Starting after 11:00 mins


          -----------------------------------------------------------------------------------------------------------------
          Acronym:
          • I - Interface(s)

          Ref:
          • https://www.youtube.com/playlist?list=PLUDwpEzHYYLu9-xrx5ykNH8wmN1C1qClk&disable_polymer=true
          Link:
          https://github.com/birobratadeb/programming-exercises/tree/main/java/Java%20Collections

          Additional Resources:
          • https://www.youtube.com/watch?v=grEKMHGYyns&t=31333s


          Comments

          Popular posts from this blog

          Coding projects

          Selenium with Python