Collections in Java
As the name collection is a group of individual objects in java. When objects are grouped it represents a single unit.
For example:- Suppose we have an individual's double roti. If we collected them it represents a single unit As shown in the given figure.
In java, the collection is a framework that contains classes and interfaces that provide to work with different collections such as Lists, Sets, Stacks, Queues, etc.
Hierarchy of Collection Framework
Iterable Interface
The Iterable interface is the root interface of all collections classes and interfaces.
Collections Interface
All the classes of Collection Framework are implemented Collection Interface. Collections Interface extends the Iterable Interface that’s why all the classes of collection framework also implement the iterable interface.
Some methods that declare in the collection interface are:-
1. add(object)
2. addAll(other collection)
3. clear()
4. isEmpty()
5. max()
6. size()
7. remove(object), etc
List Interface
List Interface directly extends the collection interface. It contains list type data Structure.
Some Properties of List Interface:-
1. It maintains the insertion order of elements.
2. It contains the duplicate value of elements.
3. It provides a facility with that element access or inserted by their indexed number.
Classes that implement the List Interface:-
1. ArrayList
2. LinkedList
3. Vector
4. Stack
List initiated as:-
List<data-type> arr = new ArrayList<data-type>();
List<data-type> arr = new LinkedList<data-type>();
List<data-type> arr = new Vector<data-type>();
List<data-type> arr = new Stack<data-type>();
ArrayList
In java, ArrayList provides the dynamic array. It will automatically shrink or grow when we remove or add elements in the ArrayList due to this nature it is slower than the normal java array.
Properties of ArrayList:-
- Java ArrayList class can contain duplicate elements.
- Java ArrayList class maintains insertion order.
- Java ArrayList allows random access because the array works on an index basis.
Example:-
import java.io.*;import java.util.*;class Add{ public static void main(String[] args){ List<Integer> arr = new ArrayList<Integer>(); for (int i = 1; i <= 5; i++){
arr.add(i);
}
System.out.println(arr); }
}
Output:- [1, 2, 3, 4, 5]
LinkedList
In java, LinkedList internally uses DoublyLinkedList to store elements that’s why we add or remove the elements from both sides. It implements List as well as Deque interfaces.
Properties of LinkedList:-
- Java LinkedList class maintains insertion order.
- Java LinkedList class can contain duplicate elements.
- In the Java LinkedList class, manipulation is fast because no shifting needs to occur.
- Java LinkedList class can be used as a list, stack or queue.
Some methods of LinkedList that are not in ArrayList:-
- addFirst(object):- It is used to insert the given element at the beginning of a list.
- addLast(object):- It is used to insert the given element at the Last of a list.
- getFirst():- It is used to return the first element in a list.
- getLast():- It is used to return the last element in a list.
- peekFirst():- It retrieves the first element of a list or returns null if a list is empty.
- peekLast():- It retrieves the last element of a list or returns null if a list is empty.
Example:-
import java.io.*;import java.util.*;class Add{public static void main(String[] args){List<Integer> arr = new LinkedList<Integer>();for (int i = 1; i <= 5; i++){
arr.add(i);
}
System.out.println(arr);}
}
Output:- [1, 2, 3, 4, 5]
Vector
Vector is the same as an ArrayList with some differences. It uses a dynamic array to store an element. Its size automatically increases or decreases when we add or remove an element. It implements a List interface.
Some Properties of Vector:-
- It is synchronized.
- It maintains insertion order.
- It contains duplicate values.
Difference between Vector and ArrayList:-
- Vector increases 100% of its size while ArrayList increases 50% of its size.
- Vector is synchronized while ArrayList not synchronized.
Some methods of Vector class:-
- capacity():- It is used to get the current capacity of this vector.
- isEmpty():- It is used to check if this vector has no components.
- add():- It is used to append the specified element in the given vector.
- clone():- It returns a clone of this vector.
- clear():- It is used to delete all of the elements from this vector.
Stack
Stack is a linear data structure that store or access the elements in the LIFO form i.e Last in First Out. In java, the Stack class extends the vector class.
Stack has some functionality or operations:-
- Top:- It represents or gives the top element index. If the stack is empty its value is (-1). If the stack is full its value is (n-1).
- Push:- It appends the element in the stack and increases the value of the top by 1.
- Pop:- It removes that element whose top pointed that index number and decrease the value of top by 1.
Methods of Stack Class:-
- push(object):- The method pushes (insert) an element onto the top of the stack.
- pop():- The method removes an element from the top of the stack and returns the same element as the value of that function.
- peek():- The method looks at the top element of the stack without removing it.
- empty():- The method checks the stack is empty or not.
Set Interface
Set Interface directly extends the Collection interface. There are many classes that implement the set interface.
- HashSet
- LinkedSet
- TreeSet
Properties of Set Interface:-
- It represents the unordered set of elements.
- It does not allow duplicate elements in the set.
- It uses the hash function internally.
- For Searching an element in the set its take only O(1) time complexity.
Set is initiated as:-
Set<data-type> s1 = new HashSet<data-type>();Set<data-type> s2 = new LinkedHashSet<data-type>();Set<data-type> s3 = new TreeSet<data-type>();
HashSet
HashSet implements the SetInterface. It uses hashing for the storage of elements.
Properties of Set Interface:-
- It represents the unordered set of elements.
- It does not allow duplicate elements in the set.
- HashSet class is non synchronized.
- HashSet allows null value.
import java.util.*;public class HashSetDemo {public static void main(String args[])HashSet<String> hs = new HashSet<String>();hs.add("India");hs.add("is");hs.add("great");hs.add("country");hs.add("in the world");Iterator<String> itr = hs.iterator();while (itr.hasNext()) {System.out.println(itr.next());}}}
Output:-
in the world
India
great
is
LinkedHashSet
LinkedHashSet implements the SetInterface.
Properties of LinkedHashSet:-
- LinkedHashSet maintains the insertion order.
- LinkedHashSet only contains unique elements just like a HashSet.
- LinkedHashSet class is not synchronized.
TreeSet
TreeSet class implement Set interface. It uses the tree for the storage of elements.
- It contains only a unique element in the TreeSet.
- It maintains the ascending order of elements.
- It is not synchronized.
Queue Interface
Queue Interface extends the collection interface. It follows the FIFO manner for remove or stores the element i.e First In First Out it is similar to as First come First service Rule.
Classes that implement Queue Interface:-
- PriorityQueue
- ArrayDeque
Methods of Queue Interface
- add(object):- It is used to insert the specified element into this queue and return true upon success.
- remove():- It is used to retrieves and removes the head of this queue.
- poll():- It is used to retrieves and removes the head of this queue, or returns null if this queue is empty.
- element():- It is used to retrieves, but does not remove, the head of this queue.
- peek():- It is used to retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.
Queue as initiated as:-
Queue<data-type> s1 = new PriorityQueue<data-type>();Queue<data-type> s2 = new ArrayDeque<data-type>();
PriorityQueue
Priority Queue implements the Queue interface. It does not follow the FIFO order instead it follows the priority heap by which it accesses or removes an element.
ArrayDeque
ArrayDeque class which is implemented in the collection framework provides us with a way to apply resizable-array. This is a special kind of array that grows and allows users to add or remove an element from both sides of the queue.
Map Interface
Map Interface is used when we need to perform an action on the basis of key and value pair. It does not allow duplicate keys in the map but duplicate values are allowed.
Classes that implement the Map Interface:-
- HashMap
- TreeMap
Map initiated as:-
Map<data-type, data-type> hm = new HashMap<data-type, data-type> ();
Map<data-type, data-type> tm = new TreeMap<data-type, data-type> ();
HashMap
HashMap implemented Map Interface which allows to store and perform actions in key and value manner. HashMap internally uses technique hashing.
It does not allow duplicate keys in Map but the duplicate value is allowed. It also searches keys in O(1) time complexity.
Properties of HashMap:-
- It does not maintain order.
- It stores the value in key and value mannner
- It does not allow duplicate keys but duplicate values are allowed.
- It is not synchronized.
Some Methods of HashMap class:-
- put(Object key, Object value):- It is used to insert an entry in the map.
- Object clone():- It is used to return a shallow copy of this HashMap instance: the keys and values themselves are not cloned.
- remove(Object key):- It is used to delete an entry for the specified key.
- size():- This method returns the number of entries in the map.
Example:-
import java.util.*;public class HashMapDemo {public static void main(String args[]){HashMap<Integer, String> hm = new HashMap<Integer, String>();hm.put(1, "India");hm.put(2, "is");hm.put(3, "country");System.out.println("Value for 1 is " + hm.get(1));for (Map.Entry<Integer, String> e : hm.entrySet())System.out.println(e.getKey() + " " + e.getValue());}}
Output:-
Value for 1 is India
1 India
2 is
3 country