Basic java learning: how to use the Enum type
This article brings you an introduction to how to use the Enum type in java. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
1. Introduction to Enum type
Enumerated type (Enumerated Type) appeared very early in programming languages and is used to a group of similar values into a type among. The name of this enumeration type will be defined as a unique type descriptor, which is similar to the definition of a constant. However, compared to constant types, enumeration types can provide a larger value range for declared variables.
For example, if you want to draw seven colors for the rainbow, you can do it through constant definition in a Java program.
Public static class RainbowColor { // 红橙黄绿青蓝紫七种颜色的常量定义 public static final int RED = 0; public static final int ORANGE = 1; public static final int YELLOW = 2; public static final int GREEN = 3; public static final int CYAN = 4; public static final int BLUE = 5; public static final int PURPLE = 6; }
When used, you can directly reference these constants in the program. However, there are still some problems with this approach.
Type is not safe
Since the corresponding value of the color constant is an integer, so It is very possible to pass an arbitrary integer value to the color variable during program execution, causing an error.
No namespace
Since color constants are just properties of the class, when you use have to be accessed through classes.
Poor consistency
Because the integer enumeration is a compile-time constant, the compilation process After completion, all client and server-side references will have integer values written directly. In this way, when you modify the old enumeration integer value or add a new enumeration value, all referenced code needs to be recompiled, otherwise errors will occur at runtime.
The type has no meaning
Because the color enumeration value is just some meaningless Integer values with any meaning, if you debug during runtime, you will find that there are many magic numbers in the log, but except for the programmer himself, it is difficult for others to understand their meaning.
2. How to define the Enum type
In order to improve The deficiencies of the Java language in this regard are made up for. When the 5.0 version of the SDK was released, enumeration types were added to the language level. The definition of an enumeration type is also very simple. Just use the enum keyword plus the name and the enumeration value body enclosed in braces. For example, the rainbow color mentioned above can be redefined using the new enum method:
#From the above definition form, it seems that the enumeration type in Java is very simple, but in fact the functions given to the enumeration type by the Java language specification are very It is so powerful that it not only simply converts integer values into objects, but also converts enumeration type definitions into a fully functional class definitions. This type definition extension allows developers to add any methods and properties to the enumeration type and implement any interface. In addition, the Java platform also provides high-quality implementations for the Enum type, such as the default implementation of the Comparable and Serializable interfaces, allowing developers to Normally you don't need to worry about these details.
回到本文的主题上来,引入枚举类型到底能够给我们开发带来什么样好处呢?一个最直接的益处就是扩大 switch 语句使用范围。5.0 之前,Java 中 switch 的值只能够是简单类型,比如 int、byte、short、char, 有了枚举类型之后,就可以使用对象了。这样一来,程序的控制选择就变得更加的方便,看下面的例子:
定义 Enum 类型
// 定义一周七天的枚举类型 public enum WeekDayEnum { Mon, Tue, Wed, Thu, Fri, Sat, Sun } // 读取当天的信息 WeekDayEnum today = readToday(); // 根据日期来选择进行活动 switch(today) { Mon: do something; break; Tue: do something; break; Wed: do something; break; Thu: do something; break; Fri: do something; break; Sat: play sports game; break; Sun: have a rest; break; }
对于这些枚举的日期,JVM 都会在运行期构造成出一个简单的对象实例一一对应。这些对象都有唯一的 identity,类似整形数值一样,switch 语句就根据此来进行执行跳转。
如何定制 Enum 类型
除了以上这种最常见的枚举定义形式外,如果需要给枚举类型增加一些复杂功能,也可以通过类似 class 的定义来给枚举进行定制。比如要给 enum 类型增加属性,可以像下面这样定义:
// 定义 RSS(Really Simple Syndication) 种子的枚举类型 public enum NewsRSSFeedEnum { // 雅虎头条新闻 RSS 种子 YAHOO_TOP_STORIES("<a href="http://rss.news.yahoo.com/rss/topstories"><code>http://rss.news.yahoo.com/rss/topstories</code></a>"), //CBS 头条新闻 RSS 种子 CBS_TOP_STORIES("<a href="http://feeds.cbsnews.com/CBSNewsMain?format=xml"><code>http://feeds.cbsnews.com/CBSNewsMain?format=xml</code></a>"), // 洛杉矶时报头条新闻 RSS 种子 LATIMES_TOP_STORIES("<a href="http://feeds.latimes.com/latimes/news?format=xml"><code>http://feeds.latimes.com/latimes/news?format=xml</code></a>"); // 枚举对象的 RSS 地址的属性 private String rss_url; // 枚举对象构造函数 private NewsRSSFeedEnum(String rss) { this.rss_url = rss; } // 枚举对象获取 RSS 地址的方法 public String getRssURL() { return this.rss_url; } }
上面头条新闻的枚举类型增加了一个 RSS 地址的属性 , 记录头条新闻的访问地址。同时,需要外部传入 RSS 访问地址的值,因而需要定义一个构造函数来初始化此属性。另外,还需要向外提供方法来读取 RSS 地址。
The above is the detailed content of Basic java learning: how to use the Enum type. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.
