Enums in Java

Last updated on Dec 23 2022
Prabhas Ramanathan

Table of Contents

Java EnumSet class

Java EnumSet class is the specialized Set implementation for use with enum types. It inherits AbstractSet class and implements the Set interface.

EnumSet class hierarchy

The hierarchy of EnumSet class is given in the figure given below.

EnumSet class declaration

Let’s see the declaration for java.util.EnumSet class.
1. public abstract class EnumSet<E extends Enum<E>> extends AbstractSet<E> implements Cloneable, Serializable

Methods of Java EnumSet class

Method Description
static <E extends Enum<E>> EnumSet<E> allOf(Class<E> elementType) It is used to create an enum set containing all of the elements in the specified element type.
static <E extends Enum<E>> EnumSet<E> copyOf(Collection<E> c) It is used to create an enum set initialized from the specified collection.
static <E extends Enum<E>> EnumSet<E> noneOf(Class<E> elementType) It is used to create an empty enum set with the specified element type.
static <E extends Enum<E>> EnumSet<E> of(E e) It is used to create an enum set initially containing the specified element.
static <E extends Enum<E>> EnumSet<E> range(E from, E to) It is used to create an enum set initially containing the specified elements.
EnumSet<E> clone() It is used to return a copy of this set.

ava EnumSet Example

 

1. import java.util.*;
2. enum days {
3. SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
4. }
5. public class EnumSetExample {
6. public static void main(String[] args) {
7. Set<days> set = EnumSet.of(days.TUESDAY, days.WEDNESDAY);
8. // Traversing elements
9. Iterator<days> iter = set.iterator();
10. while (iter.hasNext())
11. System.out.println(iter.next());
12. }
13. }

Output:
TUESDAY
WEDNESDAY

Java EnumSet Example: allOf() and noneOf()

 

1. import java.util.*;
2. enum days {
3. SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
4. }
5. public class EnumSetExample {
6. public static void main(String[] args) {
7. Set<days> set1 = EnumSet.allOf(days.class);
8. System.out.println("Week Days:"+set1);
9. Set<days> set2 = EnumSet.noneOf(days.class);
10. System.out.println("Week Days:"+set2);
11. }
12. }

Output:
Week Days:[SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY]
Week Days:[]

Java EnumMap class

Java EnumMap class is the specialized Map implementation for enum keys. It inherits Enum and AbstractMap classes.
EnumMap class hierarchy
The hierarchy of EnumMap class is given in the figure given below.

EnumMap class declaration

Let’s see the declaration for java.util.EnumMap class.
1. public class EnumMap<K extends Enum<K>,V> extends AbstractMap<K,V> implements Serializable, Cloneable

EnumMap class Parameters

Let’s see the Parameters for java.util.EnumMap class.
• K: It is the type of keys maintained by this map.
• V: It is the type of mapped values.

Constructors of Java EnumMap class

Constructor Description
EnumMap(Class<K> keyType) It is used to create an empty enum map with the specified key type.
EnumMap(EnumMap<K,? extends V> m) It is used to create an enum map with the same key type as the specified enum map.
EnumMap(Map<K,? extends V> m) It is used to create an enum map initialized from the specified map.

Methods of Java EnumMap class

SN Method Description
1 clear() It is used to clear all the mapping from the map.
2 clone() It is used to copy the mapped value of one map to another map.
3 containsKey() It is used to check whether a specified key is present in this map or not.
4 containsValue() It is used to check whether one or more key is associated with a given value or not.
5 entrySet() It is used to create a set of elements contained in the EnumMap.
6 equals() It is used to compare two maps for equality.
7 get() It is used to get the mapped value of the specified key.
8 hashCode() It is used to get the hashcode value of the EnumMap.
9 keySet() It is used to get the set view of the keys contained in the map.
10 size() It is used to get the size of the EnumMap.
11 Values() It is used to create a collection view of the values contained in this map.
12 put() It is used to associate the given value with the given key in this EnumMap.
13 putAll() It is used to copy all the mappings from one EnumMap to a new EnumMap.
14 remove() It is used to remove the mapping for the given key from EnumMap if the given key is present.

Java EnumMap Example

 

1. import java.util.*;
2. public class EnumMapExample {
3. // create an enum
4. public enum Days {
5. Monday, Tuesday, Wednesday, Thursday
6. };
7. public static void main(String[] args) {
8. //create and populate enum map
9. EnumMap<Days, String> map = new EnumMap<Days, String>(Days.class);
10. map.put(Days.Monday, "1");
11. map.put(Days.Tuesday, "2");
12. map.put(Days.Wednesday, "3");
13. map.put(Days.Thursday, "4");
14. // print the map
15. for(Map.Entry m:map.entrySet()){
16. System.out.println(m.getKey()+" "+m.getValue());
17. }
18. }
19. }

Output:
Monday 1
Tuesday 2
Wednesday 3
Thursday 4

Java EnumMap Example: Book

 

1. import java.util.*;
2. class Book {
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. this.id = id;
8. this.name = name;
9. this.author = author;
10. this.publisher = publisher;
11. this.quantity = quantity;
12. }
13. }
14. public class EnumMapExample {
15. // Creating enum
16. public enum Key{
17. One, Two, Three
18. };
19. public static void main(String[] args) {
20. EnumMap<Key, Book> map = new EnumMap<Key, Book>(Key.class);
21. // Creating Books
22. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
23. Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);
24. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
25. // Adding Books to Map
26. map.put(Key.One, b1);
27. map.put(Key.Two, b2);
28. map.put(Key.Three, b3);
29. // Traversing EnumMap
30. for(Map.Entry<Key, Book> entry:map.entrySet()){
31. Book b=entry.getValue();
32. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
33. }
34. }
35. }

Output:
101 Let us C Yashwant Kanetkar BPB 8
102 Data Communications & Networking Forouzan Mc Graw Hill 4
103 Operating System Galvin Wiley 6

So, this brings us to the end of blog. This Tecklearn ‘Enums in Java’ blog helps you with commonly asked questions if you are looking out for a job in Java Programming. If you wish to learn Java and build a career Java Programming domain, then check out our interactive, Java and JEE Training, that comes with 24*7 support to guide you throughout your learning period. Please find the link for course details:

Java and JEE Training

Java and JEE Training

About the Course

Java and JEE Certification Training is designed by professionals as per the industrial requirements and demands. This training encompasses comprehensive knowledge on basic and advanced concepts of core Java & J2EE along with popular frameworks like Hibernate, Spring & SOA. In this course, you will gain expertise in concepts like Java Array, Java OOPs, Java Function, Java Loops, Java Collections, Java Thread, Java Servlet, and Web Services using industry use-cases and this will help you to become a certified Java expert.

Why Should you take Java and JEE Training?

• Java developers are in great demand in the job market. With average pay going between $90,000/- to $120,000/- depending on your experience and the employers.
• Used by more than 10 Million developers worldwide to develop applications for 15 Billion devices.
• Java is one of the most popular programming languages in the software world. Rated #1 in TIOBE Popular programming languages index (15th Consecutive Year)

What you will Learn in this Course?

Introduction to Java

• Java Fundamentals
• Introduction to Java Basics
• Features of Java
• Various components of Java language
• Benefits of Java over other programming languages
• Key Benefits of Java

Installation and IDE’s for Java Programming Language

• Installation of Java
• Setting up of Eclipse IDE
• Components of Java Program
• Editors and IDEs used for Java Programming
• Writing a Simple Java Program

Data Handling and Functions

• Data types, Operations, Compilation process, Class files, Loops, Conditions
• Using Loop Constructs
• Arrays- Single Dimensional and Multi-Dimensional
• Functions
• Functions with Arguments

OOPS in Java: Concept of Object Orientation

• Object Oriented Programming in Java
• Implement classes and objects in Java
• Create Class Constructors
• Overload Constructors
• Inheritance
• Inherit Classes and create sub-classes
• Implement abstract classes and methods
• Use static keyword
• Implement Interfaces and use it

Polymorphism, Packages and String Handling

• Concept of Static and Run time Polymorphism
• Function Overloading
• String Handling –String Class
• Java Packages

Exception Handling and Multi-Threading

• Exception handling
• Various Types of Exception Handling
• Introduction to multi-threading in Java
• Extending the thread class
• Synchronizing the thread

File Handling in Java

• Input Output Streams
• Java.io Package
• File Handling in Java

Java Collections

• Wrapper Classes and Inner Classes: Integer, Character, Boolean, Float etc
• Applet Programs: How to write UI programs with Applet, Java.lang, Java.io, Java.util
• Collections: ArrayList, Vector, HashSet, TreeSet, HashMap, HashTable

Java Database Connectivity (JDBC)

• Introduction to SQL: Connect, Insert, Update, Delete, Select
• Introduction to JDBC and Architecture of JDBC
• Insert/Update/Delete/Select Operations using JDBC
• Batch Processing Transaction
• Management: Commit and Rollback

Java Enterprise Edition – Servlets

• Introduction to J2EE
• Client Server architecture
• URL, Port Number, Request, Response
• Need for servlets
• Servlet fundamentals
• Setting up a web project in Eclipse
• Configuring and running the web app with servlets
• GET and POST request in web application with demo
• Servlet lifecycle
• Servlets Continued
• Session tracking and filter
• Forward and include Servlet request dispatchers

Java Server Pages (JSP)

• Fundamentals of Java Server Page
• Writing a code using JSP
• The architecture of JSP
• JSP Continued
• JSP elements: Scriptlets, expressions, declaration
• JSP standard actions
• JSP directives
• Introduction to JavaBeans
• ServletConfig and ServletContext
• Servlet Chaining
• Cookies Management
• Session Management

Hibernate

• Introduction to Hibernate
• Introduction to ORM
• ORM features
• Hibernate as an ORM framework
• Hibernate features
• Setting up a project with Hibernate framework
• Basic APIs needed to do CRUD operations with Hibernate
• Hibernate Architecture

POJO (Plain Old Java Object)

• POJO (Plain Old Java Object)
• Persistent Objects
• Lifecycle of Persistent Object

Spring

• Introduction to Spring
• Spring Fundamentals
• Advanced Spring

Got a question for us? Please mention it in the comments section and we will get back to you.

 

0 responses on "Enums in Java"

Leave a Message

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