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
1. Arrays lets us store only homogenous or same kind of data or data of same type
Create Object Array or Array of object type:
This can allow us to store homogenous as well as heterogeneous data
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.
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:
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
- 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 ...:
- Used when we have objects which are to be queued in an order prior to processing
- Uses FIFO
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
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
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 collectionremoveAll(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)
Java Collections Framework-Part4 | ArrayList Concept | Hands-on
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
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 growableAccepts 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>
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 Arraysize() // 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 ArrayListal,contains(obj) // Searches for an object or element if it is present in the ArrayList. Returns True/ FalseisEmpty() // 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
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
- 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:
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
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
- 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() 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:
- All the HashSet methods are also applicable for LinkedHashSet class
- Demo --Starting at 4:35 mins
-----------------------------------------------------------------------------------------------------------------
Java Collections Framework-Part8 | Queue Concept | Hands-on
- 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):
- 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 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
- 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
- Insertion order not preserved as it uses the underlying data structure of HashTable/HashCode
- 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
Demo --Starting after 11:00 mins
-----------------------------------------------------------------------------------------------------------------
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
Post a Comment