“This is the first day of my participation in the Gwen Challenge in November. Check out the details: The last Gwen Challenge in 2021”

  • Prepare for spring recruitment or summer internship in 2022, wish you every day a hundred million points of progress! Day5

  • This article summarizes the correct Way to use Java enumerations and will be updated daily

  • For Redis Getting started to master, Concurrent Programming, please refer to my previous blog

  • Believe in yourself, the more live more strong, alive should be open, meet water bridge! Life, you give me pressure, I return you miracle!

1, the introduction of

I don’t know if you’ve seen code like this in your own projects:

public static void fruitsHandle(String fruits) { switch (fruits) { case "Apple": // TODO break; case "Banana": // TODO break; case "Orange": // TODO break; default: throw new IllegalStateException("Unexpected value: " + fruits); }}Copy the code

This is very rare, and it is not common for a method to repeat strings for comparison, but to define them as constants or uniformly extract them as constant classes. So you usually see code like this (Samba often sees code like this in her projects, but she doesn’t say anything 😄😄) :

private static final String APPLE = "Apple"; private static final String BANANA = "Banana"; private static final String ORANGE = "Orange"; public static void fruitsHandle(String fruits) { switch (fruits) { case APPLE: // TODO break; case BANANA: // TODO break; case ORANGE: // TODO break; default: throw new IllegalStateException("Unexpected value: " + fruits); }}Copy the code

We see this very often in our code; It requires the programmer to provide a set of fixed constants whose members are known at development time or compile time, which is when we should use enumerations.

An enum type is a type that consists of a set of fixed constants that make up a valid value.


2, advantages

Using enumerated types offers many advantages over defining constants directly.


2.1 Type Security

Define a simple meat enumeration and a fruit enumeration respectively

Public enum MeetEnums {BEEF, PORK, FISH; }Copy the code
Public enum FruitsEnums {APPLE, BANANA, ORANGE; }Copy the code

Let’s modify the above code and change the input parameter type

public static void fruitsHandle(FruitsEnums fruits) { switch (fruits) { case APPLE: // TODO break; case BANANA: // TODO break; case ORANGE: // TODO break; default: throw new IllegalStateException("Unexpected value: " + fruits); }}Copy the code

As you can see, defining an enumerated type brings function type safety that cannot be proxy if you define a constant

2.2 Enumerations provide more information

Enumerations are essentially a class that defines properties and methods, and we can define the desired methods in an enumeration class or extend the basic information provided by enumerations with properties.

For example, HttpStatus, the most common HttpStatus in web development, is defined as an enumerated class in the springframework, which not only contains the Http response code, but also contains the description status.

public enum HttpStatus { OK(200, "OK"), NOT_FOUND(404, "Not Found"), INTERNAL_SERVER_ERROR(500, "Internal Server Error"); private final int value; private final String reasonPhrase; private HttpStatus(int value, String reasonPhrase) { this.value = value; this.reasonPhrase = reasonPhrase; }}Copy the code

2.3 Provide more services through functions

In addition, HttpStatus has a nested Series enumeration class that assists the HttpStatus enumeration class, The current enumeration state is is1xxInformational, is2xxSuccessful, is3xxRedirection, is4xxClientError, is5xxServerError, etc.

public static enum Series { INFORMATIONAL(1), SUCCESSFUL(2), REDIRECTION(3), CLIENT_ERROR(4), SERVER_ERROR(5); private final int value; private Series(int value) { this.value = value; } public int value() { return this.value; } public static HttpStatus.Series valueOf(HttpStatus status) { return valueOf(status.value); } public static HttpStatus.Series valueOf(int statusCode) { HttpStatus.Series series = resolve(statusCode); if (series == null) { throw new IllegalArgumentException("No matching constant for [" + statusCode + "]"); } else { return series; } } @Nullable public static HttpStatus.Series resolve(int statusCode) { int seriesCode = statusCode / 100; HttpStatus.Series[] var2 = values(); int var3 = var2.length; for(int var4 = 0; var4 < var3; ++var4) { HttpStatus.Series series = var2[var4]; if (series.value == seriesCode) { return series; } } return null; }}Copy the code

2.4 Get all defined types

All enumerated classes automatically generate a values() method that returns the set of arrays currently defining the enumerated class, making it easy to walk through all the enumerations defined by the class. For example, let’s change the MeetEnums enumeration class briefly:

Public enum MeetEnums {BEEF(" BEEF "), PORK(" FISH "); String name; public String getName() { return name; } MeetEnums(String name) { this.name = name; } public static MeetEnums getMeetEnumsByName(String name) { MeetEnums[] values = values(); Optional<MeetEnums> optional = Stream.of(values).filter(v -> v.getName().equals(name)).findAny(); return optional.isPresent() ? optional.get() : null; }}Copy the code

Enumerated classes have many advantages over constants in that they make code cleaner, safer, and more powerful. Although most of the time, enumerated classes are chosen because constants are defined, it is not always necessary to define constants as enumerations; Specific case everybody can go weighing oneself!