Java basic induction enumeration
This article brings you relevant knowledge about java, which mainly introduces issues related to enumeration, including the basic operations of enumeration, the support of enumeration by collection classes, etc. Let’s take a look at the content below, I hope it will be helpful to everyone.
Recommended study: "java Video Tutorial"
Enumeration is to allow the access to variables of a certain type The value can only be one of several fixed values, otherwise the compiler will report an error. Enumeration allows the compiler to control the illegal values assigned by the source program during compilation. This cannot be achieved during the development stage by using ordinary variables. One goal.
After JDK1.5, use the keyword enum to define a new type, called the enumeration type
Enumeration (enum) and class (class), interface ( interface) are at the same level
Case introduction
Define a color, and only three colors, red, green and blue, can be defined
Normal method
So how to solve this problem so that color can only choose one of the three colors? ? ?
Enum class and enum keyword
The enumeration class defined using the enum keyword is actually equivalent to defining a class, and this class inherits Class Enum class only.
public enum Color { RED, GREEN, BLUE;}
Commonly used enumeration methods
##protected Enum(String name,int ordinal)
This construction The method cannot be called directly from the outside and can only be accessed by its subclasses. This constructor is automatically called
public final String name()Returns the name of the enumeration
public String toString ()Returns the name of the enumeration
public final int ordinal()Returns the serial number of the enumeration, starting from 0 by default
public final boolean equals(Object other)Judge whether two enumerations are the same
Code
public class EnumTest { public static void main(String[] args) { //定义一个color变量,只能设置为RED、GREEN、BLUE Color color = Color.BLUE; System.out.println(color); System.out.println(color.name()); System.out.println(color.toString());//三种方式都是打印名字 System.out.println(color.ordinal());//返回枚举的序号RED--0、GREEN--1、BLUE--2 Color[] values = Color.values();//返回所有枚举类型 System.out.println(Arrays.toString(values)); }}
The essence of an enumeration is a subclass that inherits the Enum class. The JVM compiler compiles the enumeration and generates afinal class
Enumerations are not allowed to be called from the outside, so they can only be privately modified
The constructor can only be called in the object
public enum Color { RED(10), GREEN(20), BLUE; private int Number;//属性 private Color() {//默认构造方法 System.out.println("无参构造器被调用了!!!"); } private Color(int Number) { this.Number = Number; System.out.println("有参构造器被调用了!!!"); } public int getNumber(){ return Number; }}
Main method
public class EnumTest { public static void main(String[] args) { Color color = Color.RED; System.out.println(color.name()); System.out.println(color.getNumber());//获取Number的值 }}
In an enumeration type, you can inherit the interface. There are two ways to implement the interface, either implement the method in the enumeration class, or implement the method inside the object
Method 1: In Implement the methods in the interface inside the enumeration object
interface info{ public String getColor();}public enum Color implements info{ RED{ @Override public String getColor() {return "红色";} }, GREEN{ @Override public String getColor() {return "绿色";} }, BLUE{ @Override public String getColor() {return "蓝色";} };}
Method 2: Implement the methods in the interface in the enumeration class
interface info{ public String getColor();}public enum Color implements info{ RED,GREEN,BLUE; @Override public String getColor() { return null; }}
Main method
public class EnumTest { public static void main(String[] args) { Color color = Color.RED; System.out.println(color.getColor()); }}
In enumeration types, abstract methods can be defined, which are implemented by objects
Enumeration class
public enum Color { RED{ @Override public String getColor() {return "红色";} }, GREEN{ @Override public String getColor() {return "绿色";} }, BLUE{ @Override public String getColor() {return "蓝色";} }; //在枚举中定义一个抽象方法,通过枚举对象实现 public abstract String getColor();}
Main method
public class EnumTest { public static void main(String[] args) { Color color = Color.BLUE; System.out.println(color.getColor()); }}
The enumeration is used to ensure that the data is within the specified range. If there is only one type (one value) in the enumeration, then there is only one object in the enumeration, then you can Implement the singleton pattern.
Enumeration class
public enum Singletion { SINGLETION; public void Method(){ System.out.println("使用枚举实现单例模式!!!"); }}
Main method
public class EnumTest { public static void main(String[] args) { Singletion singletion=Singletion.SINGLETION; singletion.Method(); }}
After JDK1.5, two new subclasses have been added to the Set and Map interfaces:EnumSet
and
EnumMapTwo subcategories
EnumSet
一个专门
Set
实现与枚举类型一起使用。 枚举集中的所有元素都必须来自创建集合时明确或隐式指定的单个枚举类型EnumSet
是一个抽象类,不能直接创建实例对象,但是可以通过方法来使用。EnumSet.allOf(Class<e> elementType)</e>
把一个枚举类型全部填充到集合中去public static <e extends enum>> EnumSet<e> complementOf(EnumSet<e> s)</e></e></e>
创建与指定枚举集具有相同元素类型的枚举集,最初包含此类型的所有元素,该元素 不包含在指定的集合中。public static <e extends enum>> EnumSet<e> copyOf(EnumSet<e> s)</e></e></e>
创建与指定的枚举集相同的元素类型的枚举集,最初包含相同的元素(如果有)
代码
import java.util.EnumSet;public class EnumTest { public static void main(String[] args) { EnumSet<color> set = EnumSet.allOf(Color.class);//把一个枚举类型全部填充到集合中去 for (Color c : set) { System.out.println(c.name()); } }}</color>
EnumMap
EnumMap
一个专门Map实现与枚举类型键一起使用。 枚举映射中的所有密钥必须来自创建映射时明确或隐式指定的单个枚举类型。 枚举地图在内部表示为数组。 这种表示非常紧凑和高效。
代码
import java.util.EnumMap;public class EnumTest { public static void main(String[] args) { EnumMap<color> map = new EnumMap(Color.class); map.put(Color.RED, "红色"); map.put(Color.GREEN, "绿色"); map.put(Color.BLUE, "蓝色"); System.out.println(map.get(Color.RED)); }</color>
推荐学习:《java视频教程》
The above is the detailed content of Java basic induction enumeration. 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

AI Hentai Generator
Generate AI Hentai for free.

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



Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

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

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

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

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo
