Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
enum | enum & Stream API
Java Data Structures
course content

Contenido del Curso

Java Data Structures

Java Data Structures

1. Basic Data Structures
2. Additional Data Structures
3. Map
4. enum & Stream API

bookenum

Let's move on to another quite interesting and, most importantly, distinctive data structure - enum.

Note

In case you've forgotten, a constant is an unchangeable value. It remains constant.

Let's take a look at creating an enum. Creating an enum differs significantly from other data structures, as it is done at the class level:

java

DaysOfTheWeek

copy
123456789
public enum DaysOfTheWeek { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }

Enum is needed so that we can easily refer to the constant. Since it's a list of constants, we access it in the following way:

java

main

copy
123456789101112131415161718
package com.example; public class Main { public static void main(String[] args) { Days today = Days.MONDAY; System.out.println(today); } } enum Days { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }

Here, we simply access the enum constant to understand which day it is today. Instead of creating many different constants, we just store an array of constants in the enum. This is convenient and very practical. For example, in one of the previous challenges, we could have stored department names in an enum and used the constant as a key.

Let's look at an example:

java

main

copy
12345678910111213141516171819202122232425262728293031323334353637
package com.example; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Main { public static void main(String[] args) { List<String> marketingEmployees = new ArrayList<>(); marketingEmployees.add("Michael"); marketingEmployees.add("Alice"); marketingEmployees.add("Jimmy"); List<String> developerEmployees = new ArrayList<>(); developerEmployees.add("Bob"); developerEmployees.add("John"); developerEmployees.add("Ryan"); List<String> analyticsEmployees = new ArrayList<>(); analyticsEmployees.add("Alexander"); analyticsEmployees.add("Ben"); Map<Departments, List<String>> company = new HashMap<>(); company.put(Departments.MARKETING, marketingEmployees); company.put(Departments.DEVELOPMENT, developerEmployees); company.put(Departments.ANALYTICS, analyticsEmployees); System.out.println("Company: " + company); } } enum Departments { MARKETING, DEVELOPMENT, ANALYTICS }

By the way, we can also retrieve all constant values from an enum as an array using the values() method.

Let's take a look at an example:

java

main

copy
12345678910111213
package com.example; public class Main { public static void main(String[] args) { Days[] array = Days.values(); Days monday = array[1]; System.out.println(monday); } } enum Days { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }

We can also declare fields and methods in enums.

Let's consider an example of a traffic light:

java

main

copy
12345678910111213
enum TrafficLight { RED("Stop"), YELLOW("Slow down"), GREEN("Go"); private final String action; TrafficLight(String action) { this.action = action; } public String getAction() { return action; } }

In enums, methods work slightly differently. Since they are constants, they cannot be modified. Therefore, we add fields in the constructor of this enum, after which we define the getAction() method that immediately outputs the action to be taken for a specific traffic light. As you can see, we specify this action directly in the enum when enumerating constants.

Let's look at an example of calling such a method:

java

main

copy
1234567891011121314151617181920212223
package com.example; public class Main { public static void main(String[] args) { TrafficLight currentLight = TrafficLight.RED; String currentAction = currentLight.getAction(); System.out.println("Action: " + currentAction); } } enum TrafficLight { RED("Stop"), YELLOW("Slow down"), GREEN("Go"); private final String action; TrafficLight(String action) { this.action = action; } public String getAction() { return action; } }

As you can see, with the help of the getAction() method, we immediately obtained the action to be taken for a specific traffic light. You can change RED to any other color and see what happens.

Methods and fields in enums are not used as often, but this functionality is present, so it's good to be aware of it. You can read more about enums in the Official Java documentation.

Let's summarize a bit:

Advantages of Enum in Java:

  1. Improved readability: Replacing numerical constants and string literals with named values makes the code more readable;
  2. Type safety: The compiler ensures type safety when working with enums, preventing type-related errors;
  3. Limited set of values: Enums provide a fixed set of values, making the code more predictable;
  4. Ability to add methods and fields: Enums can contain methods and fields, making them more powerful compared to simple enumerations.
1. What is an enum in Java?
2. How do you declare an enum called `Months` representing the months of the year?
3. How can you obtain an array of all values in an enum called `Colors`?
4. Which of the following statements about the following enum is true?
5. How would you correctly compare `currentStatus` with `Status.ACTIVE`? Consider the following enum:
What is an enum in Java?

What is an enum in Java?

Selecciona la respuesta correcta

How do you declare an enum called `Months` representing the months of the year?

How do you declare an enum called Months representing the months of the year?

Selecciona la respuesta correcta

How can you obtain an array of all values in an enum called `Colors`?

How can you obtain an array of all values in an enum called Colors?

Selecciona la respuesta correcta

Which of the following statements about the following enum is true?

Which of the following statements about the following enum is true?

Selecciona la respuesta correcta

How would you correctly compare `currentStatus` with `Status.ACTIVE`? Consider the following enum:

How would you correctly compare currentStatus with Status.ACTIVE? Consider the following enum:

Selecciona la respuesta correcta

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 4. Capítulo 1
some-alt