Skip to content
Avinandan Bose edited this page Jan 26, 2023 · 2 revisions

Java Collection Framework and Java-Set

This is all about Java Collection.

java.util →Package contains the collection classes let us to group elements in various ways . The Collection Classes also define several methods that provide easier way of working with items . These classes are important , not just for their but because many other Java methods use or return objects of these classes such as the ArrayList and HashMap classes. Collection package added to JSE 1.2 Java SE 8 has significantly increased the power and streamlined the use of collection framework.

The Collection Framework Interfaces

  • 1.Collection

  • 2.Deque

  • 3.List

  • 4.Set

  • 5.Map

  • 6.Sorted Set

  • 7.Sorted Map

  • 8.Queue

  • 9.Navigable Set

1. The Collection Interface


Collection: It is the top of the collection hierarchy. It supports basic grouping of elements.

The Collection interface is the foundation upon which the Collections Framework is built because it must be implemented by any class that defines a collection.Collection is a generic interface that has this declaration:

interface Collection<E>

Here E specifies the type of objects that the Collection will hold. Consider an example:

Collection<String> co

The above example can be a List, a Set, or another kind of Collection.

    Interface Hash Table Resizable Array Balanced Tree Linked List
    Collection HashSet ArrayList TreeSet Linked List

    That is we can create an instance of HashSet, ArrayList, TreeSet 
    and LinkedList Class,through the help of Collection interface.
    
    

    2 . Sets

    graph TD;
        Collection-->Set;
        Set-->HashSet;
        Set-->SortedSet;
        HashSet-->LinkedHashSet;
        SortedSet-->NavigableSet;
        NavigableSet-->TreeSet;
        
    
    Loading
    Collection: It is the top of the collection hierarchy. It supports basic grouping of elements.
    
    Set: It extends Collection to implement sets, in which all elements must be unique.
    
    SortedSet: It extends Set to implement a sorted set.
    
    HashSet:  It extends Set to implement a hash set.
    
    LinkedListSet:   It extends HashSet to implement a Linked List Set.
    
    NavigableSet:   It extends SortedSet to implement a Navigable Set.
    
    Tree Set:   It extends NavigableSet to implement a Tree Set.
    graph TD;
        
        Set-->HashSet;
        Set-->TreeSet;
       
        
    
    Loading
    Interface Hash Table Resizable Array Balanced Tree Linked List
    Set HashSet TreeSet
That is we can create an instance of TreeSet, HashSet,
through the help of Set Interface.

:HashSet:
___________
→It implements Set Interface.
→ Every elements entered are unique i.e. No duplicates.
→ HashSet stores the elements by using a mechanism called hashing.
→ HashSet allows null value.
→ HashSet doesn't maintain the insertion order. 
  Here, elements are inserted on the basis of their hashcode.
  
:TreeSet:
___________
→It implements Set Interface.
→TreeSet class access and retrieval times are quiet fast.
→TreeSet class doesn't allow null element.
→TreeSet class maintains ascending order. 
→TreeSet class contains unique elements only like HashSet.

Calculation of HashCode
:HASH CODE OF INTEGERS:

HASH CODE OF 1 → 1
HASH CODE OF 2 → 2
HASH CODE OF 3 → 3

                  ......etc.
                  
:HASH CODE OF STRINGS:

HASH CODE OF A → 65 //ASCII CODE
HASH CODE OF B → 66 //ASCII CODE
HASH CODE OF C → 67 //ASCII CODE
                    ......etc.

HashSet Functionality:

      Adds the specified element to this set if it is not already present. 
     More formally, adds the specified element e to this set if this set ,
     contains no element e2 such that Objects.equals(e, e2). 
     If this set already contains the element, the call leaves 
     the set unchanged and returns false.     
  • 2. Remove

  •       Removes the specified element from this set if it is present. 
          More formally, removes an element e such that Objects.equals(o, e), 
          if this set contains such an element. 
          Returns true if this set contained the element.     
  • 3. Clear

  •      Removes all of the elements from this set. 
         The set will be empty after this call returns. 
  • 4. Clone

  •       Returns a shallow copy of this HashSet instance: the elements themselves are not cloned.
  • 5. Iterator

  •       Iterator: It iterates over the elements in the set. 
          The elements are returned in no particular order.
          
          Note: The double colon (::) operator, 
          also known as method reference operator.
          
          →Double Colon Operator is used to call a method,
          by referring to it with the help of its class directly.
  • a. HashSet [Iterator] → For Each Remaining

  •      Performs the given action for each remaining element,
         until all elements have been processed or
         the action throws an exception. Actions are performed,
         in the order of iteration, if that order is specified. 
         Exceptions thrown by the action are relayed to the caller.
  • b. HashSet [Iterator] → hasNext

  •     Returns true if the iteration has more elements. 
        (In other words, returns true if next would return ,
        an element rather than throwing an exception.)
  • c. HashSet [Iterator] →Next

  •    Returns the next element in the iteration.
  • Next.CompareTo

  •   Compares two Integer objects numerically.
  • d. HashSet [Iterator] →remove

  •   Removes from the underlying collection the last element,
      returned by this iterator (optional operation).
      This method can be called only once per call to next.
  • 6. HashSet →[Union]AddAll

  •  Adds all of the elements in the specified collection to this ,
     set if they're not already present (optional operation). 
     If the specified collection is also a set, the addAll operation,
     effectively modifies this set so that its value is the union of the two sets. 
     The behavior of this operation is undefined,
     if the specified collection is modified while the operation is in progress.
  • 7. HashSet →[Intersection]RetainAll

  •  Retains only the elements in this collection that are contained,
     in the specified collection (optional operation)[Intersection]. In other words, 
     removes from this collection all of its elements that are not ,
     contained in the specified collection.
  • 8. HashSet →Spliterator

  •  Returns a Spliterator over the elements in this set.
     Creates a late-binding and fail-fast Spliterator,
     over the elements in this set.A late-binding Spliterator,
     binds to the source of elements means HashSet,
     at the point of first traversal, first split,
     or first query for estimated size, 
     rather than at the time the Spliterator is created.
  • 9. HashSet →Contains

  •  Returns true if this set contains the specified element. 
     More formally, returns true if and only if this set contains,
     an element e such that Objects.equals(o, e).
  • 10. HashSet →Size

  •  Returns the number of elements in this set (its cardinality).
  • 11. HashSet →isEmpty

  •  Returns true if this set contains no elements.

  • 12. HashSet →ContainsAll

  • From: java.util.AbstractCollection 
    
    Def: Returns true if this collection contains all of the elements,
    in the specified collection.
    
  • 13. HashSet →RemoveAll

  • From: java.util.AbstractSet
    
    Def: Removes from this set all of its elements ,
    that are contained in the specified collection (optional operation). 
    If the specified collection is also a set, this operation effectively modifies,
    this set so that its value is the asymmetric set difference of the two sets.
    
    This implementation determines which is the smaller of this set and the specified collection, 
    by invoking the size method on each. If this set has fewer elements, then the implementation ,
    iterates over this set, checking each element returned by the iterator,
    in turn to see if it is contained in the specified collection.
    
    
  • 14. HashSet →RemoveIf

  • From: java.util.Collection
    
    Def: Removes all of the elements of this collection that satisfy the given predicate. 
    Errors or runtime exceptions thrown during iteration or ,
    by the predicate are relayed to the caller.
    
    
  • 15. HashSet →Stream

  • From: java.util.Collection
    
    Def: Returns a sequential Stream with this collection as its source.
    
  • 16. HashSet →ParallelStream

  • From: java.util.Collection
    
    Def: Returns a possibly parallel Stream with this collection as its source. 
    It is allowable for this method to return a sequential stream.
    

    Note:Parallel Stream has similar functions like Streams.

  • 17. HashSet →toArray

  • From: java.util.Collection
    
    Def: Returns an array containing all of the elements in this collection; 
    the runtime type of the returned array is that of the specified array. 
    If the collection fits in the specified array, it is returned therein. 
    Otherwise, a new array is allocated with the runtime type of the specified array 
    and the size of this collection.
    
  • 18. HashSet →equals

  • From: java.util.AbstractSet
    
    Def: Compares the specified object with this set for equality. 
    Returns true if the given object is also a set, 
    the two sets have the same size, 
    and every member of the given set is contained in this set. 
    
  • 19. HashSet →toString

  • From: java.util.AbstractCollection
    
    Def: Converts the set to string and returns the collection.
    
  • 19. HashSet →hashCode

  • From: java.util.AbstractSet
    
    Def: Returns the hash code value for this set. 
    The hash code of a set is,
    defined to be the sum of the hash codes of the elements in the set, 
    where the hash code of a null element is defined to be zero. 
    

    sequenceDiagram
        
      
      java.lang.Object->>java.util.AbstractCollection: 
      java.util.AbstractCollection->>java.util.AbstractSet: 
      java.util.AbstractSet->>java.util.HashSet: 
    
    Loading

    Abstract Set

     We can create instance of HashSet from Abstract Set.
     AbstractSet class in Java is a part of the Java Collection Framework,
     which implements the Collection interface and extends,
     the AbstractCollection class. It provides a skeletal implementation,
     of the Set interface. 

    Abstract Collection

     We can create instance of HashSet from Abstract Collection.
     The AbstractCollection class in Java is a part of the ,
     Java Collection Framework and implements the Collection interface. 
     It is used to implement an unmodifiable collection, 
     for which one needs to only extend this AbstractCollection Class 
     and implement only the iterator and the size methods. 

    Object[java.lang.Object]

     We can create instance of HashSet from Object → [java.lang.Object].

    TreeSet Functionality:

    sequenceDiagram
        
      
      java.lang.Object->>java.util.AbstractCollection: 
      java.util.AbstractCollection->>java.util.AbstractSet: 
      java.util.AbstractSet->>java.util.TreeSet: 
    
    Loading

    Def: Java TreeSet class implements the Set interface that uses a tree for storage. It inherits AbstractSet class and implements the NavigableSet interface and SortedSet interface. The objects of the TreeSet class are stored in ascending order.

    Interface Hash Table Resizable Array Balanced Tree Linked List
    Set HashSet TreeSet
    NavigableSet TreeSet SortedSet TreeSet

    Continuing...: Java TreeSet class implements most of the functions that Hash Set uses as given below:

    Continuing...: As TreeSet implements Set , Navigable Set and SortedSet interface , hence it uses functions of Set , NavigableSet and SortedSet interface.

    Extras

     It takes Float value in the Function.
     Returns the least element in this set greater than or equal to the given element, 
     or null if there is no such element. 
     It returns the Ceil value of the Float Value ,entered in the ceiling function.
  • It takes Float value in the Function.
    Returns the greatest element in this set less than or equal to the given element, 
    or null if there is no such element. 
    It returns the Floor value of the Float Value ,entered in the Floor function.
  • It takes Float value in the Function.
    
    :Higher:
    ----------------
    Higher Func: Returns the greatest element in the Set corresponding to the number set in Higher Function.
    Where, the number set in the Function must be present in the given set.
    Set: [50.58 , 20.78, 30.65, 10.78, 50.98, 60.65,30.65]
    Higher: set.higher(30.65) = 50.58
    
    
    :Lower:
    ----------------
    Lower Func: Returns the lowest element in the Set corresponding to the number set in Lower Function.
    Where, the number set in the Function must be present in the given set.
    Set: [50.58 , 20.78, 30.65, 10.78, 50.98, 60.65,30.65]
    Lower: set.lower(30.65) = 20.78
    
  • Descending Iterator: Returns an iterator over the elements in this set in descending order.
    It has all functions like it have in Iterator i.e. CompareTo, Next , hasNext . 
    
  • First: Returns first (lowest)element in the set.
    i.e. set = [2,3,4,1,5,6] , then it will return 1.
    
    Last: Returns last (highest)element in the set.
    i.e. set = [2,3,4,1,5,7,6] , then it will return 7.
  • Poll First: Retrieves and removes the first (lowest) element, or returns null if this set is empty.
    i.e. set = [2,3,4,1,5,6] , then it will return 1.
    And set will be : [2,3,4,5,6]
    
    Poll Last: Retrieves and removes the last (highest) element, or returns null if this set is empty.
    i.e. set = [2,3,4,1,5,7,6] , then it will return 7.
     And set will be : [2,3,4,1,5,6]

  • Implemented From : java.util.SortedSet
    It returns Sub Set i.e. From a Starting Element to the Last Element.
    i.e. if Set = [1,2,3,4,5,6];
    And Subset :→ From Element : 2 
    And To Element: 6
    IT will return set: [3,4,5]
  • Implemented From : java.util.NavigableSet
    It returns Sub Set i.e. From a Starting Element to the Last Element.
    i.e. if Set = [1,2,3,4,5,6];
    And Subset :→ From Element : 2 , boolean fromInclusive : true
    And To Element: 6 ,  boolean toInclusive : false
    IT will return set: [2,3,4,5]
    
    Similarly:
    
    Subset :→ From Element : 2 , boolean fromInclusive : false
    And To Element: 6 , boolean toInclusive : false
    IT will return set: [3,4,5]
    
  • Implemented From : java.util.SortedSet
    It returns Set from a Starting Element set to TailSet function.
    i.e. if Set = [1,2,3,4,5,6];
    And tailset :→ From Element : 2 
    IT will return set: [2,3,4,5,6]
  • Implemented From : java.util.SortedSet
    It returns Set upto a Ending Element but not the Ending Element set to HeadSet function.
    i.e. if Set = [1,2,3,4,5,6];
    And To Element: 6 ,
    IT will return set: [1,2,3,4,5]
    
  • Implemented From : java.util.NavigableSet
    It returns Set from a Starting Element set to TailSet function if Boolean Inclusive set to True,
    Else returns Set from a Starting Element set to TailSet function except the Starting Element ,
    if Boolean Inclusive set to False.
    
    i.e. if Set = [1,2,3,4,5,6];
    And tailset :→ From Element : 2
    And inclusive : true
    IT will return set: [2,3,4,5,6]
    
    Else:
    
    tailset :→ From Element : 2
    And inclusive : false
    IT will return set: [3,4,5,6]
    
  • Implemented From : java.util.NavigableSet
    It returns Set upto a Ending Element but not the Ending Element set to HeadSet function,
    if Boolean Inclusive set to True,
    Else It returns Set upto a Ending Element with the Ending Element set to HeadSet function,
    if Boolean Inclusive set to False.
    
    i.e. if Set = [1,2,3,4,5,6];
    And HeadSet :→ To Element : 6
    And inclusive : True
    IT will return set: [1,2,3,4,5]
    
    Else:
    
    tailset :→ To Element : 6
    And inclusive : false
    IT will return set: [1,2,3,4,5,6]
    
  • Implemented From : java.util.NavigableSet
    
    It makes the output of Set in Descending Order i.e. From ,
    Greatest Element to Lowest Element. 
     

    Comparator Interface on Tree Set

      Comparator helps to find the sorting order used in the TreeSet objects ; for example, with the implementation of the Comparator interface.The methods provided by the interface are:

      Methods of the Comparator interface
      Method Does This
      int compare(Object obj1,Object obj2) It compares its two arguments.
      boolean equals(Object obj) It specifies whether another object is equal to this comparator.

    LinkedHashSet

    This class extends HashSet, but adds no members of its own. LinkedHashSet is an ordered and sorted collection of HashSet. LinkedHashSet maintains the insertion order of the elements.It uses a doubly linked list to maintain the insertion order. LinkedHashSet implement the Set interface like HashSet.

    sequenceDiagram
        
      
      java.lang.Object->>java.util.AbstractCollection: 
      java.util.AbstractCollection->>java.util.AbstractSet: 
      java.util.AbstractSet->>java.util.HashSet: 
      java.util.HashSet->>java.util.LinkedHashSet: extends
    
    Loading

    About Sorted Set Interface

      The Sorted Set interface Set extends Set and declares the behavior of a set sorted in ascending order. Sorted Set is a generic interface that has this declaration:

      interface SortedSet<E>
      

      Here E specifies the type of objects that the Set will hold.

      Interface Methods
      SortedSet first
      last
      headSet
      tailSet
      subSet

    About Navigable Set Interface

      The NavigableSet interface extends SortedSet and declares the behavior of a collection that supports the retrieval of elements based on the closest match to a given value or values. NavigableSet is a generic interface that has this declaration :

      interface NavigableSet<E>
      

      Here E specifies the type of objects that the Set will hold.

      Interface Methods
      NavigableSet ceiling
      floor
      descendingIterator
      descendingSet
      headSet
      tailSet
      subSet
      higher
      lower
      pollFirst
      pollLast

    Note: Collection , Set, SortedSet, Navigable Set are all interfaces and we cannot create their objects due their abstract nature.

    About AbstractCollection

      The AbstractCollection class is an Abstract Class provides an implementation of the Collection interface. It is used to implement an unmodifiable collection, for which one needs to only extend this AbstractCollection Class and implement only the iterator and the size methods.

     
     abstract class AbstractCollection<E> extends Object implements Collection<E>
     

    where E is the type of elements.

    Abstract Class Methods
    AbstractCollection Add
    AddAll
    Clear
    Contains
    ContainsAll
    isEmpty
    Iterator
    Remove
    Size
    toArray
    toString

    About AbstractSet

    AbstractSet is an Abstract class in Java is a part of the Java Collection Framework which implements the Collection interface and extends the AbstractCollection class. It provides a skeletal implementation of the Set interface.

      
      abstract class AbstractSet<E> extends AbstractCollection<E> implements Set<E>
      

    Where E is the type of elements.

    Abstract Class Method/s
    AbstractSet removeAll
    equals
    hashCode
      
     graph TD;
        Collection-->|extends| Set;
        Collection-->|implements| AbstractCollection;
        Set-->|extends| AbstractSet;
        Set-->|extends| SortedSet;
        SortedSet-->|extends| NavigableSet;
        NavigableSet-->|implements| ConcurrentSkiplistSet;
        AbstractCollection-->|extends| AbstractSet;
        AbstractSet-->|extends| CopyOnWriteArraySet;
        AbstractSet-->|extends| HashSet;
        HashSet-->|extends| LinkedHashSet;
        AbstractSet-->|extends| TreeSet;
        AbstractSet-->|extends| EnumSet;
        AbstractSet-->|extends| ConcurrentSkiplistSet;
      
    
    Loading

    Hence we get three more types :

    • 1. EnumSet

    • 2. CopyOnWriteArraySet

    • 3. ConcurrentSkipListSet

    EnumSet

    • A specialized Set implementation for use with enum [Enumeration] types.

    • All of the elements in an enum set must come from a single enum type that is specified, explicitly or implicitly, when the set is created.

    • It extends AbstractSet class and implements Set Interface in Java.

    • EnumSet class is a member of the Java Collections Framework .

    • HashSet and TreeSet can also take the type of ENUM and add ENUM constants to perform Set operations.

    • EnumSet inherits methods from Collection.

    • Enum Set also had its Methods as listed below:

    • Class Method/s
      EnumSet of
      allOf
      clone
      complementOf
      copyOf
      range
      noneOf
    • Examples:

      
      Creates an enum set initially containing the specified elements.
      
  •   
      Creates an enum set containing all of the elements in the specified element type.
      
  •   
      Returns copy of a set.
      
  •   
    Creates an enum set with the same element type as the specified enum set, 
    initially containing all the elements of this type,
    that are not contained in the specified set.
      
  •   
    Creates an enum set with the same element type,
    as the specified enum set, 
    initially containing the same elements (if any).
      
  •   
    Creates an enum set initially containing all of the elements,
    in the range defined by the two specified endpoints. 
      
  •   
    Creates an empty enum set with the specified element type. 
      

    CopyOnWriteArraySet

    • To use this class, we need to import it from java.util.concurrent package.

    • CopyOnWriteArraySet is a member of the Java Collections Framework.

    • It is a Set that uses an internal CopyOnWriteArrayList for all of its operations.

    • It was introduced in JDK 1.5, we can say that it is a thread-safe version of Set.

    • That is Multiple Threads are able to perform update operations simultaneously but for every update operation, a separate cloned copy is created.

    • While one thread iterating the Set, other threads can perform updation.

    • Iterators returned are fail-safe.

    • It is synchronized.

    • An Iterator of CopyOnWriteArraySet class can perform only read-only and should not perform the deletion, otherwise, we will get Run-time exception UnsupportedOperationException.

    • It is slower compared to HashSet since it is synchronized.

    • Class Method/s
      CopyOnWriteArraySet add
      addAll
      clear
      contains
      containsAll
      equals
      forEach
      isEmpty
      iterator
      remove
      removeAll
      removeIf
      retainAll
      size
      spliterator
      toArray
      Class Inherited From Method/s
      CopyOnWriteArraySet AbstractSet hashCode
      Class Inherited From Method/s
      CopyOnWriteArraySet AbstractCollection toString
      Class Inherited From Method/s
      CopyOnWriteArraySet Collection Stream
      Parallel Stream

    ConcurrentSkipListSet

    • The ConcurrentSkipListSet class in Java is a part of the Java Collection Framework .

    • The ConcurrentSkipListSet class in Java implements the Collection interface and the AbstractSet class .

    • The ConcurrentSkipListSet class is a scalable concurrent NavigableSet implementation based on a ConcurrentSkipListMap.

    • The elements of the ConcurrentSkipListSet are kept sorted according to their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used.

    • The ConcurrentSkipListSet class implements Serializable, Cloneable, Iterable, Collection, NavigableSet, Set, SortedSet interfaces.

    • The ConcurrentSkipListSet does not allow null elements, because null arguments and return values cannot be reliably distinguished from the absence of elements.

    • The ConcurrentSkipListSet is thread-safe.

    • The ConcurrentSkipListSet Methods :

      Class Method/s
      ConcurrentSkipListSet add
      ceiling
      floor
      clear
      clone
      comparator
      contains
      descendingIterator
      descendingSet
      equals
      first
      last
      headSet
      tailSet
      higher
      lower
      pollFirst
      pollLast
      remove
      removeAll
      size
      spliterator
      subSet
      isEmpty
      Class Inherited From Method/s
      ConcurrentSkipListSet AbstractCollection addAll
      containsAll
      retainAll
      toArray
      toArray(T[] a)
      toString
      Class Inherited From Method/s
      ConcurrentSkipListSet Set addAll
      containsAll
      retainAll
      toArray
      toArray(T[] a)
      hashCode
      Class Inherited From Method/s
      ConcurrentSkipListSet Collection parallelStream
      Stream
      removeIf
      Class Inherited From Method/s
      ConcurrentSkipListSet java.lang.Iterable Iterable
      java.util.Iterator forEach
    Clone this wiki locally