coderz.py

Keep Coding Keep Cheering!

EnumSet in Java

java thread class
What is EnumSet in Java?
  • The EnumSet is a specialized implementation of the Set interface designed for use with enumeration types.
  • It derives from the AbstractSet class and implements the Set interface.
  • Enum sets are internally represented as bit vectors. This is a very compact and efficient representation.
  • This class’s space and time performance should be sufficient to allow it to be used as a high-quality, typesafe alternative to traditional int-based “bit flags.” Even bulk operations (such as containsAll and retainAll) should be very fast if their argument is also an enum set.
Syntax:
public abstract class EnumSet<E extends Enum<E>> 

where E specifies the elements.

Methods of EnumSet Class:
MethodDescription
allOf​(Class<E> elementType)Creates an enum set that contains all elements of the specified element type.
clone()Returns a copy of this set.
complementOf​(EnumSet<E> s)Creates an enum set with the same element type as the specified set, initially containing all elements of this type that are not in the specified set.
copyOf​(Collection<E> c)Generates an enum set from the specified collection.
copyOf​(EnumSet<E> s)Creates an enum set with the same element type as the specified enum set, with the same elements at first (if any).
noneOf​(Class<E> elementType)This method generates an empty enum set with the specified element type.
of​(E e)Creates an enum set with the specified element as the first element.
range​(E from, E to)Creates an enum set with all of the elements in the range defined by the two endpoints specified.
Example:

import java.util.EnumSet;

// Enum
enum Week { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY,FRIDAY,SATURDAY };

// Main class

public class COderz {

 // Main driver method
 public static void main(String[] args) {

  // Creating a set
  EnumSet<Week> set1, set2, set3, set4;

  // Adding elements
  set1 = EnumSet.of(Week.SATURDAY, Week.MONDAY,
      Week.FRIDAY, Week.SUNDAY);
  set2 = EnumSet.complementOf(set1);
  set3 = EnumSet.allOf(Week.class);
  set4 = EnumSet.range(Week.WEDNESDAY, Week.SATURDAY);

  // Printing corresponding elements in Sets
  System.out.println("Set 1: " + set1);
  System.out.println("Set 2: " + set2);
  System.out.println("Set 3: " + set3);
  System.out.println("Set 4: " + set4);
 }
}
Output:
Set 1: [SUNDAY, MONDAY, FRIDAY, SATURDAY]
Set 2: [TUESDAY, WEDNESDAY, THURSDAY]
Set 3: [SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY]
Set 4: [WEDNESDAY, THURSDAY, FRIDAY, SATURDAY]

Note: also read about the AbstractSet in Java

Follow Me

If you like my post, please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

One Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Advertisement