Set Interface
- Set is a collection of unique objects and it does not allow duplicates.
- HashSet implementation uses hashtable for storing these objects.
- LinkedHashSet implementation uses linked list for storing these objects. Insertion/Delete thus, are fast here.
- TreeSet implementation uses a tree for storing these objects in sorted order. Hence searching is fastest here.
Types of Sets
- Java provides several implementations of the Set interface, including HashSet, LinkedHashSet, and TreeSet.
- HashSet:-uses a hash table for storage, making it efficient for most use cases.
- LinkedHashSet:-maintains the insertion order of elements.
- TreeSet:-stores elements in a sorted order.
Adding Elements
- To add elements to a Set, use the add method.
- Example:
Set set = new HashSet<>();
set.add("apple");
set.add("banana");
Map Interface
- Map contains the objects as key-value pair
- The keys in the Map are unique, but the values could be duplicate.
- Some of the methods are put(Object,Object), get(Object), remove(Object), keySet(), entrySet() etc.
- Entry is a inner class of map and is accessed via Map.Entry and has methods, getKey() and getValue().
Map Interface(Continued…)
- HashMap implementation can have one null key and it maintains no order of the elements stored.
- HashTable also an implementation of Map, does not allow null key values and is synchronised.
- LinkedHashMap also acts like a HashMap, but it maintains the natural insertion order of elements.
- TreeMap cannot have null key and it maintains the elements in ascending order
Queue Interface
- Queue interface typically, but not necessarily keeps the elements in the FIFO order.
- Some of the methods of this interface are add(Object), remove(), poll(), peek() etc.
- A typical implementation of the Queue is a LinkedList and PriorityQueue(this maintains the elements in natural order).
Types of Queues
- Java provides several implementations of the Queue interface, including LinkedList, ArrayDeque, and PriorityQueue.
- LinkedList:-can be used as a general-purpose queue.
- ArrayDeque:- is a double-ended queue that supports efficient insertion and removal at both ends.
- PriorityQueue:-is a priority-based queue, where elements are ordered by their natural order or a specified comparator.
Adding Elements (Enqueue)
- To add elements to a queue, use the add or offer method.
- Example:
Queue queue = new LinkedList<>();
queue.add("apple");
queue.offer("banana");
Sets and queues are fundamental data structures in Java that can be used to solve a wide range of programming problems. Understanding their characteristics and choosing the appropriate implementation is essential for efficient and correct programming.