DEV Community

Preethi Nandhagopal
Preethi Nandhagopal

Posted on

LinkedHashSet and Queue

LinkedHashSet:

  • A LinkedHashSet is a class in Java that:
  • Implements the Set interface
  • It is part of java.util package.

Key Features:

  1. Unique Elements -> Like all sets, it does not allow duplicates.
  2. Maintains Insertion Order -> Unlike HashSet (which is unordered), LinkedHashSet keeps elements in the same order you inserted them.
  3. Allows null -> Can store one null element.
  4. Performance -> Almost same as HashSet (O(1) average time for add, remove, contains).
  5. Slightly slower than HashSet because it also maintains a linked list for order.

Methods in LinkedHashSet:

  1. Since it extends HashSet, it has the same methods:
  2. add(E e) – add element
  3. remove(Object o) – remove element
  4. contains(Object o) – check if present
  5. size() – number of elements
  6. clear() – remove all elements
  7. isEmpty() – check if empty

Queue:

  • Queue is a collection interface used to hold elements before processing, typically in FIFO (First-In-First-Out) order.
  • It is part of the Java Collections Framework and defined in:
  • java.util.Queue

Key Points:

  1. Interface → Queue is an interface, not a class.
  2. Order → Elements are usually processed in FIFO order, though some implementations (like PriorityQueue) order them differently.
  3. Duplicates → Allowed.
  4. Nulls → Some implementations allow one null (like LinkedList), but PriorityQueue does not.

Common Queue Methods:
(Specializes methods of Collection)

  1. boolean add(E e) Inserts element, throws exception if full
  2. boolean offer(E e) Inserts element, returns false if full
  3. E remove() Removes head, throws exception if empty
  4. E poll() Removes head, returns null if empty
  5. E element() Retrieves head, throws exception if empty
  6. E peek() Retrieves head, returns null if empty

Top comments (0)