Table of Contents
Case introduction
Enum class and enum keyword
Commonly used enumeration methods
EnumSet
EnumMap
Home Java javaTutorial Java basic induction enumeration

Java basic induction enumeration

May 26, 2022 am 11:50 AM
java

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.

Java basic induction enumeration

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
Java basic induction enumeration
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;}
Copy after login

Java basic induction enumeration

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

Java basic induction enumeration

Basic operations of enumerations

Enumeration with constructor

The essence of an enumeration is a subclass that inherits the Enum class. The JVM compiler compiles the enumeration and generates a

final class

Enumerations are not allowed to be called from the outside, so they can only be privately modified
Java basic induction enumeration
The constructor can only be called in the object
Java basic induction enumeration

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

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

Java basic induction enumeration

Enumeration implementation interface

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

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

Main method

public class EnumTest {
    public static void main(String[] args) {
        Color color = Color.RED;
        System.out.println(color.getColor());
    }}
Copy after login

Java basic induction enumeration

Enumeration implements abstract methods

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

Main method

public class EnumTest {
    public static void main(String[] args) {
        Color color = Color.BLUE;
        System.out.println(color.getColor());
    }}
Copy after login

Java basic induction enumeration

Enumeration implementation Singleton mode

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("使用枚举实现单例模式!!!");
    }}
Copy after login

Main method

public class EnumTest {
    public static void main(String[] args) {
        Singletion singletion=Singletion.SINGLETION;
        singletion.Method();
    }}
Copy after login

Java basic induction enumeration

Collection Class support for enumeration

After JDK1.5, two new subclasses have been added to the Set and Map interfaces:

EnumSet and EnumMap Two subcategories

EnumSet

一个专门Set实现与枚举类型一起使用。 枚举集中的所有元素都必须来自创建集合时明确或隐式指定的单个枚举类型
EnumSet是一个抽象类,不能直接创建实例对象,但是可以通过方法来使用。Java basic induction enumeration
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>
Copy after login

Java basic induction enumeration

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

Java basic induction enumeration

推荐学习:《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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

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

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

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

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

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

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

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

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

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

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

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.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

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

How to Run Your First Spring Boot Application in Spring Tool Suite? How to Run Your First Spring Boot Application in Spring Tool Suite? Feb 07, 2025 pm 12:11 PM

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

See all articles