Home > Java > javaTutorial > Basic java learning: how to use the Enum type

Basic java learning: how to use the Enum type

青灯夜游
Release: 2018-10-19 16:50:42
forward
2292 people have browsed it

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; 
}
Copy after login

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; 
}
Copy after login

对于这些枚举的日期,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; 
   } 
}
Copy after login

上面头条新闻的枚举类型增加了一个 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!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template